如何在WinForms中遗留错误时显示Messagebox“数据无效”. 尝试了类似但不起作用的东西. if (errorprovider1 == !null){ MessageBox.Show("Data is invalid");} 也许我必须使用bool来解决这个问题. 我的完整代
尝试了类似但不起作用的东西.
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. }您应该首先以这种方式更正您的验证事件:
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
方法检查是否存在验证错误,然后你可以获得所有错误的列表并以这种方式显示给用户:
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<Control>() .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,“”);
>当出现验证错误时,您应该调用e.Cancel = true.
>在示例代码中,我假设您的所有控件(包括错误提供程序)都直接放在您的表单上,而不是放在容器控件中.
>我还建议通过在表单的Load事件中按代码的设计时间将表单的AutoValidate属性设置为EnableAllowFocusChange来更改表单的验证行为:
要更改表单的验证行为:
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;