c# – 使用Validating事件和ErrorProvider进行验证 – 显示错误
发布时间:2020-12-16 01:21:09 所属栏目:百科 来源:网络整理
导读:如何在WinForms中遗留错误时显示Messagebox“数据无效”. 尝试了类似但不起作用的东西. if (errorprovider1 == !null){ MessageBox.Show("Data is invalid");} 也许我必须使用bool来解决这个问题. 我的完整代码: private void Form1_Load(object sender,Eve
如何在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. } 解决方法
您应该首先以这种方式更正您的验证事件:
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,""); } } 然后你应该使用 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); } } 示例截图: 注意: >你不应该使用 要更改表单的验证行为: this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |