使用Validating事件和ErrorProvider进行validation – 显示错误摘要
如何在WinForms中遗留错误时显示Messagebox“数据无效”。 尝试过类似但不起作用的东西。
if (errorprovider1 == !null) { MessageBox.Show("Data is invalid"); }
也许我必须使用bool来解决这个问题。
我的完整代码:
private void Form1_Load(object sender, EventArgs e) { this.Text = "Formas elementu validācija"; } private void textBox1_Validating(object sender, CancelEventArgs e) { Regex regex1 = new Regex(@"^[a-zA-Z]+$"); if (!regex1.IsMatch(textBox1.Text)) { errorProvider1.SetError(textBox1, "Nosaukums nedrīskt saturēt ciparus!"); } else { errorProvider1.Clear(); } } private void textBox2_Validating(object sender, CancelEventArgs e) { Regex regex1 = new Regex(@"^[0-9]+$"); if (!regex1.IsMatch(textBox2.Text)) { errorProvider2.SetError(textBox2, "Reģ.nur drīkst saturēt TIKAI ciparus!"); } else { errorProvider2.Clear(); } } private void button1_Click(object sender, EventArgs e) { // if errorProvider1 is empty (no errors) , show messagebox with text: All data correct. // else Data is incorrect. }
您应该首先以这种方式更正您的validation事件:
private void textBox1_Validating(object sender, CancelEventArgs e) { Regex regex1 = new Regex(@"^[a-zA-Z]+$"); if (!regex1.IsMatch(textBox1.Text)) { //To set validation error errorProvider1.SetError(textBox1, "Nosaukums nedrīskt saturēt ciparus!"); //To say the state of control in invalid e.Cancel = true; } else { //To clear the validation error this.errorProvider1.SetError(this.textBox1, ""); } }
然后,您应该使用ValidateChildren
方法检查是否存在validation错误,然后您可以获取所有错误的列表并以这种方式显示给用户:
private void button1_Click(object sender, EventArgs e) { if (this.ValidateChildren()) { //Here the form is in valid state //Do what you need when the form id valid } else { var listOfErrors = this.errorProvider1.ContainerControl.Controls.Cast() .Select(c => this.errorProvider1.GetError(c)) .Where(s => !string.IsNullOrEmpty(s)) .ToList(); MessageBox.Show("Please correct validation errors:\n - " + string.Join("\n - ", listOfErrors.ToArray()), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
示例截图:
注意:
- 您不应该使用
Clear
方法的错误提供程序来设置要控制的有效状态,您应该使用SetError
,例如this.errorProvider1.SetError(textBox2, "");
- 当出现validation错误时,您应该调用
e.Cancel=true
。 - 在示例代码中,我假设您的所有控件(包括错误提供程序)都直接放在您的表单上,而不是放在容器控件中。
- 我还建议通过在表单的
Load
事件中按代码的设计时间将表单的AutoValidate
属性设置为EnableAllowFocusChange
来更改表单的validation行为:
要更改表单的validation行为:
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;