How can I check multiple textboxes if null or empty without a unique test for each?

42,597

Solution 1

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.
        }
    }
}

Solution 2

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
}
Share:
42,597
Fuzz Evans
Author by

Fuzz Evans

Updated on August 23, 2020

Comments

  • Fuzz Evans
    Fuzz Evans almost 4 years

    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?