Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating multiple textboxes using errorprovider

Tags:

c#

winforms

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?

like image 216
user1584253 Avatar asked Aug 26 '12 11:08

user1584253


3 Answers

Yes, there is.

First, you need to obtain all the text boxes in form of a sequence, for instance like this:

var boxes = Controls.OfType<TextBox>(); 

Then, you can iterate over them, and set the error accordingly:

foreach (var box in boxes)
{
    if (string.IsNullOrWhiteSpace(box.Text))
    {
        errorProvider1.SetError(box, "Please fill the required field");
    }
}

I would recommend using string.IsNullOrWhiteSpace instead of x == "" or + string.IsNullOrEmpty to mark text boxes filled with spaces, tabs and the like with an error.

like image 122
Adam Avatar answered Nov 16 '22 08:11

Adam


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");
        }
    }
like image 43
aravind Avatar answered Nov 16 '22 09:11

aravind


Edit:

var controls = new [] { tx1, tx2. ...., txt10 };
foreach(var control in controls.Where(e => String.IsNullOrEmpty(e.Text))
{
    errorProvider1.SetError(control, "Please fill the required field");
}
like image 1
Candide Avatar answered Nov 16 '22 08:11

Candide