如何检查多个文本框是否为空,而无需为每个文本框编写唯一的测试?

10

我有一个表单上大约有20个文本框,用户可以填写。如果他们在任何一个文本框中输入了任何内容,我想提示用户考虑保存。目前这个测试非常冗长而混乱:

if(string.IsNullOrEmpty(txtbxAfterPic.Text) || string.IsNullOrEmpty(txtbxBeforePic.Text) ||
            string.IsNullOrEmpty(splitContainer1.Panel2) ||...//many more tests

我能否使用类似任意类型数组的内容,其中该数组由文本框组成,并通过这种方式进行检查?还有哪些其他非常方便的方法可以用来查看自程序启动以来是否有任何更改?

还有一件事情要提到的是,有一个日期时间选择器。我不知道是否需要在该日期时间选择器周围进行测试,因为datetimepicker永远不会为空。

编辑: 我将答案添加到我的程序中,但似乎无法正常工作。 我按以下方式设置了测试,并不断触发Application.Exit()调用。

        //it starts out saying everything is empty
        bool allfieldsempty = true;

        foreach(Control c in this.Controls)
        {
            //checks if its a textbox, and if it is, is it null or empty
            if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))
            {
                //this means soemthing was in a box
               allfieldsempty = false;
               break;
            }
        }

        if (allfieldsempty == false)
        {
            MessageBox.Show("Consider saving.");
        }
        else //this means nothings new in the form so we can close it
        {                
            Application.Exit();
        }

为什么基于以上代码,我的文本框中没有找到任何文本?
3个回答

26

当然可以 - 通过枚举你的控件查找文本框:

foreach (Control c in this.Controls)
{
    if (c is TextBox)
    {
        TextBox textBox = c as TextBox;
        if (textBox.Text == string.Empty)
        {
            // Text box is empty.
            // You COULD store information about this textbox is it's tag.
        }
    }
}

对我来说,它无法识别"this.Controls"。是否需要先进行某些导入?已经尝试过"using System.Windows.Forms;"了。 - señor.woofers

13

在George的回答基础上,利用一些方便的LINQ方法:

if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))  
{
//Your textbox is empty
}

1
附注:标准的文本框控件在其文本属性中永远不会返回空值。不过,LINQ 的使用很好!+1 - George Johnston
1
你的答案更好,因为它只会弹出一次消息框。而“foreach”语句会多次弹出MessageBox.Show("Please enter all info")。 - Serge V.

0
public void YourFunction(object sender, EventArgs e) {
    string[] txtBoxArr = { textBoxOne.Text, textBoxTwo.Text, textBoxThree.Text };
    string[] lblBoxArr = { "textBoxOneLabel", "textBoxTwoLabel", "textBoxThreeLabel" };
    TextBox[] arr = { textBoxOne, textBoxTwo, textBoxThree };

    for (int i = 0; i < txtBoxArr.Length; i++)
    {
        if (string.IsNullOrWhiteSpace(txtBoxArr[i]))
        {
            MessageBox.Show(lblBoxArr[i] + " cannot be empty.");
            arr[i].Focus();
            return;
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接