【问题标题】:Windows Forms Application: How to Check for Empty Textboxes When Submit Button Is Clicked?Windows 窗体应用程序:单击提交按钮时如何检查空文本框?
【发布时间】:2016-09-17 18:54:31
【问题描述】:

在我的 Windows 窗体应用程序中,我有一组来自 textBox1 - textBox20 的文本框和一个提交按钮 (button1)。

当我按下点击提交按钮时,如何遍历我的所有文本框以检查其中是否有任何一个为空,然后显示一个消息框,说“文本框 #____ 不能为空”?

当我点击提交按钮时,我还想显示用户输入到文本框中的所有数据。

我对使用 Windows 窗体非常陌生,所以我需要帮助。

【问题讨论】:

标签: c# forms validation textbox windows-forms-designer


【解决方案1】:

基于您手动创建文本框并且它们的编号为 1-20 的事实,您可以执行以下操作:

 private void checkTextBoxes(){
    List<string> textValues = new List<string>();
    bool emptyFound = false;
    for(int i=1;i<21;i++){
       TextBox t = this.Controls.Find("TextBox"+i.ToString(),true)[0] as TextBox;
       //use parent control if you have one ex: Panel1.Controls.Find
       if(t.Text.Length==0){
           emptyFound=true;
           break;
       }
       textValues.Add(t.Text);
    }
    if(emptyFound){
        MessageBox.Show("You left a textbox blank");
    }else{
        MessageBox.Show("You entered values:\n"+String.Join("\n",textValues));
    }
 }

【讨论】:

    【解决方案2】:

    你可以试试这个

    private void TextBoxEmpty()
        {
            StringBuilder result = new StringBuilder();
            bool emptyTextbox = false;
            for (int i = 1; i <= 20; i++)
            {
                try
                {
                    TextBox myTextBox = (TextBox)Controls.Find("textBox" + i.ToString(), true)[0];
                    if (string.IsNullOrEmpty(myTextBox.Text))
                    {
                        MessageBox.Show(myTextBox.Name + " cannot be left empty");
                        emptyTextbox = true;
                        continue;
                    }
                    result.Append(myTextBox.Text + Environment.NewLine);
                }
                catch
                {
                    continue;
                }
            }
            if (!emptyTextbox)
                MessageBox.Show(result.ToString());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      相关资源
      最近更新 更多