Alex Rivera | Logout

Validating multiple textboxes using errorprovider

Asked 2012-08-26T11:43:45.600
9

I have 10 textboxes, now i want to check that none of them are empty when a button is clicked. My code is :

 if (TextBox1.Text == "")
 {
    errorProvider1.SetError(TextBox1, "Please fill the required field");
 }

Is there any way that I can check all the textboxes at once, rather than writing for every individual?

Edit
Report

1 Answer

2

Might not be an optimal solution but this also should work

    public Form1()
    {
       InitializeComponent();
       textBox1.Validated += new EventHandler(textBox_Validated);
       textBox2.Validated += new EventHandler(textBox_Validated);
       textBox3.Validated += new EventHandler(textBox_Validated);
       ...
       textBox10.Validated += new EventHandler(textBox_Validated);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.ValidateChildren();
    }

    public void textBox_Validated(object sender, EventArgs e)
    { 
        var tb = (TextBox)sender;
        if(string.IsNullOrEmpty(tb.Text))
        {
            errorProvider1.SetError(tb, "error");
        }
    }
answered 2012-08-26T11:49:25.123

Your Answer