使用errorprovidervalidation多个文本框

我有10个文本框,现在我想检查单击按钮时它们都不是空的。 我的代码是:

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

有什么方法可以一次检查所有文本框,而不是为每个人写作?

就在这里。

首先,您需要以序列的forms获取所有文本框,例如:

 var boxes = Controls.OfType(); 

然后,您可以迭代它们,并相应地设置错误:

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

我建议使用string.IsNullOrWhiteSpace而不是x == ""或+ string.IsNullOrEmpty来标记填充了空格,制表符等的文本框,并显示错误。

编辑:

 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"); } 

可能不是最佳解决方案,但这也应该有效

  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"); } }