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();
        }

为什么根据上面的代码在我的文本框中找不到任何文本?

4

2 回答 2

27

当然——枚举你的控件寻找文本框:

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.
        }
    }
}
于 2012-01-05T21:47:12.923 回答
13

基于 George 的回答,但使用了一些方便的 LINQ 方法:

if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))  
{
//Your textbox is empty
}
于 2012-01-05T21:49:33.150 回答