How to check multiple text fields if they are empty or empty, without a unique test for each?

I have about 20 text fields in a form that a user can fill out. I want to invite the user to consider saving if they have anything entered in any text field. Now the test for this is very long and dirty:

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

Is there a way to use something like an array of any where the array is made from text fields, and I check it this way? What other ways can be a very convenient way to see if any changes have been made since the program started?

Another thing I should mention is the timing. I do not know if I need to check this, since the datetimepicker will never be empty or empty.

EDIT: I have included the answers in my program, but I cannot get it to work correctly. I installed the tests as shown below and continue to run 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 doesn't he find text in text fields based on the code above?

+9
arrays c # text testing isnullorempty
source share
2 answers

Of course - list the text fields through your controls:

 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 tag. } } } 
+26
source share

Building George's answer, but using some convenient LINQ methods:

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

All Articles