Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding which textbox is empty

I have short windows program I use to add information quickly. But now I'm trying to enhance it. Was looking for a more efficient want to check for empty text boxes and if the box was empty to find which one it was and set the focus back to only that box. Currently I loop through all of them and check to see if any box was empty if it is just display a message. But have to look to see which box is missing text. Heres 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);
}
like image 205
Troy Bryant Avatar asked Sep 12 '14 19:09

Troy Bryant


1 Answers

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

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

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

like image 179
Rahul Tripathi Avatar answered Sep 19 '22 16:09

Rahul Tripathi