我有10个文本框,现在我想检查它们当单击按钮时是否为空。 我的代码是:使用错误提供程序验证多个文本框
if (TextBox1.Text == "")
{
errorProvider1.SetError(TextBox1, "Please fill the required field");
}
有没有办法,我可以一次检查所有的文本框,而不是写每一个人的什么办法?
我有10个文本框,现在我想检查它们当单击按钮时是否为空。 我的代码是:使用错误提供程序验证多个文本框
if (TextBox1.Text == "")
{
errorProvider1.SetError(TextBox1, "Please fill the required field");
}
有没有办法,我可以一次检查所有的文本框,而不是写每一个人的什么办法?
是的,有。
首先,你需要获得一个序列中的表单中的所有文本框,比如像这样:
var boxes = Controls.OfType<TextBox>();
然后,你可以通过它们迭代,并相应设置错误:
foreach (var box in boxes)
{
if (string.IsNullOrWhiteSpace(box.Text))
{
errorProvider1.SetError(box, "Please fill the required field");
}
}
我建议使用string.IsNullOrWhiteSpace
而不是x == ""
或+ string.IsNullOrEmpty
来标记填充空格,制表符等错误的文本框。
可能不是一个最佳的解决方案,但是这也应该工作
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");
}
}
编辑:
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");
}
这几乎可以肯定是Windows窗体,而不是asp.net。 – Adam