Validating multiple textboxes using errorprovider

后端 未结 3 1192
慢半拍i
慢半拍i 2021-02-03 15:06

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.Se         


        
3条回答
  •  借酒劲吻你
    2021-02-03 15:20

    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(); 
    

    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.

提交回复
热议问题