如果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.
}
答案 0 :(得分:2)
您应该首先以这种方式纠正您的验证事件:
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
。AutoValidate
表单的EnableAllowFocusChange
属性设置为Load
代码的this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
形式的代码:更改表单的验证行为:
{{1}}