views:

749

answers:

6

I use C#. I have a Windows Form with an edit box and a Cancel button. The edit box has code in validating event. The code is executed every time the edit box loses focus. When I click on the Cancel button I just want to close the form. I don't want any validation for the edit box to be executed. How can this be accomplished?

Here is an important detail: if the validation fails, then

            e.Cancel = true;

prevents from leaving the control.

But when a user clicks Cancel button, then the form should be closed no matter what. how can this be implemented?

+1  A: 

Set the CausesValidation property of the Cancel button to false.

womp
A: 

Set the CausesValidation property to false.

Brandon
A: 

Judicious use of the Control.CausesValidation property will help you achieve what you want.

Joe
+3  A: 

If the validation occurs when the edit box loses focus, nothing about the the cancel button is going to stop that from happening.

However, if the failing validation is preventing the cancel button from doing its thing, set the CausesValidation property of the button to false.

Reference: Button.CausesValidation property

Daniel Schaffer
Not sure why someone down-voted this. For a winforms application, it is true. The other three answers are incorrect.
Stewbob
It wasn't me :D
Daniel Schaffer
+1  A: 

Obviously CausesValidation property of the button has to be set to false and then the validating event will never happen on its click. But this can fail if the parent control of the button has its CausesValidation Property set to true. Most of the time developers misses/forgets to change the CausesValidation property of the container control (like the panel control). Set that also to False. And that should do the trick.

Vimal Raj
A: 

Setting CausesValidation to false is the key, however this alone is not enough. If the buttons parent has CausesValidation set to true, the validating event will still get called. In one of my cases I had a cancel button on a panel on a form, so I had to set CausesValidation = false on the panel as well as the form. In the end I did this programatically as it was simpler than going through all the forms...

Control control = cancelButton;

while(control != null)
{
   control.CausesValidation = false;
   control = control.Parent;
}
Steve Sheldon