Text field search

I have a small window program that I use to quickly add information. But now I'm trying to improve it. I needed a more effective option for checking empty text fields, and if the box was empty to find what it was, and set the focus back only to this field. I am currently reviewing all of them and checking to see if there was an empty field if it just displays a message. But you need to see in which field the text is missing. Here is the code:

bool txtCompleted = true; string errorMessage = "One or more items were missing from the form"; foreach(Control c in Controls) { if (c is TextBox) { if (String.IsNullOrEmpty(c.Text)) { txtCompleted = false; } } } if (txtCompleted == false) { MessageBox.Show(errorMessage); } 
+5
source share
3 answers

Set focus on the control during the cycle, and then break when done.

  foreach(Control c in Controls) { if (c is TextBox) { if (String.IsNullOrEmpty(c.Text)) { txtCompleted = false; c.Focus(); MessageBox.Show(errorMessage); break; } } } 
+2
source

Your approach using foreach looks promising to me. How can you use LINQ as well

 if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)) { ... } 

You can use the focus() method to set focus to an empty text field.

+6
source

To get a link to an empty text field, you use almost the same solution as RT , but use FirstOrDefault instead:

 var emptyTextBox = Controls.OfType<TextBox>().FirstOrDefault(t => string.IsNullOrEmpty(t.Text) if (emptyTextBox != null) { // there is a textbox that has no Text set // set focus, present error message etc. on emptyTextBox } 
+1
source

Source: https://habr.com/ru/post/1202446/


All Articles