How can I check if all textboxes are empty?

Asked

Viewed 2,285 times

0

Code:

if (string.IsNullOrWhiteSpace(txtNumero.Text) && string.IsNullOrWhiteSpace(txtTitle.Text))
{
    MessageBox.Show("Preencha todas as informações");
}

I tried to do with && and it doesn’t work, how can I do it? I want to check two or more textboxs

  • 3

    && I mean, the two of you have to be empty, so if one of you is, you can’t get into your if, change to ||

  • Ah it was silly thing haha, thank you.

1 answer

2


If you want to check all textBoxes the best way and create a dynamic method(imagine a registration screen where you have a large amount of textBoxes)

private bool textBoxVazias()
{
   foreach (Control c in this.Controls)
      if (c is TextBox)
      {
         TextBox textBox = c as TextBox;
         if (string.IsNullOrWhiteSpace(textBox.Text))
            return true;
      }
    return false;
}

After creating the method, just call it and if the return is positive, some textbox is empty.

if(textBoxVazias()) MessageBox.Show("Preencha todas as informações");

If you still prefer to specify the fields, or if they are few as in your example, just use || (or) instead of && (and)

if (string.IsNullOrWhiteSpace(txtNumero.Text) || string.IsNullOrWhiteSpace(txtTitle.Text))
    MessageBox.Show("Preencha todas as informações");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.