C# 使用errorprovider验证多个文本框
我有10个文本框,现在我想检查当点击一个按钮时没有一个是空的。 我的代码是:C# 使用errorprovider验证多个文本框,c#,winforms,C#,Winforms,我有10个文本框,现在我想检查当点击一个按钮时没有一个是空的。 我的代码是: if (TextBox1.Text == "") { errorProvider1.SetError(TextBox1, "Please fill the required field"); } 有没有什么方法可以让我一次检查所有的文本框,而不是为每个人写?可能不是一个最佳的解决方案,但这也应该有效 public Form1() { InitializeComponent(
if (TextBox1.Text == "")
{
errorProvider1.SetError(TextBox1, "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");
}
}
编辑:
是的,有
首先,您需要以序列的形式获取所有文本框,例如:
var boxes = Controls.OfType<TextBox>();
我建议使用
string.IsNullOrWhiteSpace
而不是x==”
或+string.IsNullOrEmpty
来将充满空格、制表符等的文本框标记为错误。这几乎肯定是Windows窗体,而不是asp.net。
var boxes = Controls.OfType<TextBox>();
foreach (var box in boxes)
{
if (string.IsNullOrWhiteSpace(box.Text))
{
errorProvider1.SetError(box, "Please fill the required field");
}
}