How to show Messagebox \"Data is invalid\" when there is errors left in my WinForms. Tried something like but it does not work.
if (errorprovider1 == !null)
You should first correct your validating events this way:
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, "");
}
}
Then you should use ValidateChildren method to check if there is a validation error or not, then you can get a list of all errors and show to user this way:
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);
}
}
A Sample screenshot:
Note:
this.errorProvider1.SetError(textBox2, "");
e.Cancel=true
when there is a validation error.AutoValidate
property of form to EnableAllowFocusChange
in design time of by code in Load
event of form this way:To change validation behavior of form:
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;