I have a close button on my form that I've set to CausesValidation = false
. But when I run it and try to close it with ErrorProvider in effect it won't let me close. I've even tried adding to the close routine errorProvider1.Clear()
or errorProvider1.Dispose() but
still no luck closing the form until I take care of the error.
What I have found to work is in the close if I loop over all the controls and set CausesValidation=false
then it works as expected by closing the form despite any errors present.
private void btnAdd_Click(object sender, EventArgs e)
{
if (!this.ValidateChildren()) return;
DoAddCommand();
}
private void DoAddCommand()
{
//input
string input1 = textBox1.Text;
string input2 = textBox2.Text;
//process
this.ValidateChildren();
decimal sum = Class1.Add(input1, input2);
//output
lblSum.Text = sum.ToString();
}
private void textBoxNumberEntry_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextBox textBox = sender as TextBox;
decimal number1 = 0;
try
{
number1 = decimal.Parse(textBox.Text);
errorProvider1.Clear();
}
catch (FormatException)
{
errorProvider1.SetError(textBox, "Enter a valid number");
e.Cancel = true;
}
}
private void btnClose_Click(object sender, EventArgs e)
{
foreach (Control item in this.Controls)
{
item.CausesValidation = false;
}
this.Close();
}
Try adding those two attributes in your asp:Button
tag
CausesValidation="false"
UseSubmitBehavior="false"
The CauseValidation
should be enough, but I believe because you have a server side OnCLick
event you also need to specify the SubmitBehavior.
Mario
Most likely what is happening is that one of the TextBoxes have the focus at the time you try to hit the Cancel button, so the validation is already occurring. Your solution works by going through the controls and setting the the CausesValidation property back to False.
A short-cut method is to just turn off the form's AutoValidate property:
private void btnClose_Click(object sender, EventArgs e)
{
this.AutoValidate = AutoValidate.Disable;
this.Close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With