C# 使用 errorprovider 验证多个文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12129824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating multiple textboxes using errorprovider
提问by user1584253
I have 10 textboxes, now i want to check that none of them are empty when a button is clicked. My code is :
我有 10 个文本框,现在我想检查当单击按钮时它们都不是空的。我的代码是:
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?
有什么方法可以一次检查所有文本框,而不是为每个人都写?
采纳答案by Adam
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.IsNullOrWhiteSpaceinstead of x == ""or + string.IsNullOrEmptyto mark text boxes filled with spaces, tabs and the like with an error.
我建议使用string.IsNullOrWhiteSpace而不是x == ""或 +string.IsNullOrEmpty来标记填充有空格、制表符等错误的文本框。
回答by aravind
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");
}
}
回答by Candide
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");
}

