How to check if all Textbox is empty in on click and input thier errorProvider msg?

365 Views Asked by At

I want to check if any textbox is empty on btn click and then display their corresponding SetError msg on their side

bool isIncomplete = false;
foreach (Control control in this.Controls)
{
    if (control is TextBox)
    {
        TextBox tb = control as TextBox;
        if (string.IsNullOrWhiteSpace(tb.Text))
        {
            isIncomplete = true;
            break;
        }
    }
} // I think this.controls does not work properly..

if (isIncomplete)
{
    errorProvider1.SetError(firstname_txtbox, "First Name is required.");
    errorProvider2.SetError(lastname_txtbox, "Last Name is required.");

    MessageBox.Show("Please fill all the textbox correctly!");
    return;

} else if(firstname_txtbox.Text.Length < 2)
{ 
  errorProvider1.SetError(firstname_txtbox, "First Name need to be at least 2 characters"); //this error message does appear through...
}else if() { etc..

The errorProvider message arent being dispalyed on click. My textboxes are inside a Panel...

1

There are 1 best solutions below

0
On

use String.IsNullOrEmpty(String) to check if a control is empty.

private void button1_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(textBox1.Text))
        {
            MessageBox.Show("Please fill all the textbox correctly!");
        }
        else
        {
            MessageBox.Show("Not empty");
        }
    }