How can I check multiple textboxes if null or empt

2019-01-17 13:18发布

I have about 20 text fields on a form that a user can fill out. I want to prompt the user to consider saving if they have anything typed into any of the text boxes. Right now the test for that is really long and messy:

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

Is there a way I could use something like an Array of any, where the array is made of the text boxes and I check it that way? What other ways might be a very convenient way in which to see if any changes have been made since the program started?

One other thing I should mention is there is a date time picker. I don't know if I need to test around that as the datetimepicker will never be null or empty.

EDIT: I incorporated the answers into my program, but I can't seem to make it work correctly. I set up the tests as below and keep triggering the Application.Exit() call.

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

Why is it not finding any text in my text boxes based on the code above?

2条回答
小情绪 Triste *
2楼-- · 2019-01-17 13:32

Building on George's answer, but making use of some handy LINQ methods:

if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))  
{
//Your textbox is empty
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-17 13:37

Sure -- enumerate through your controls looking for text boxes:

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.
        }
    }
}
查看更多
登录 后发表回答