tags:

views:

35

answers:

1

This is a winform C# question. I have a textbox with a validating event listener to validate the content of the textbox. Say, the textbox doesn't accept negative values. I only listen to validating event so by default, the textbox's AutoValidate property is EnablePreventFocusChange, which is totally fine for me.

The problem is, when I click the X button on the right top corner of the form, I don't want the validation to be fired because I am closing the form anyway. How can I do this? There is no control to set CauseValidation to false, which I can do if there is a closing button. Thank you very much.

+1  A: 

Hmmm, the only way I would think to do it is to set AutoValidate on the form to false and handle validation in the controls manually. The form has .Validate() and .ValidateChildren() methods, read up on these as they are what you need to perform validation. To handle it manually, you will need to listen for when a control is losing focus - if validation fails you then need to perhaps re-focus the offending control.

Alternatively, make the form ControlBox = false; to remove the X button.

Update: Alternatively again you can use a member variable to test whether to validate or not (ie, whether the form is closing or not). You cannot do this using the FormClosing event as this fires after the validation, however you can detect form closing via WndProc. Code is provided in this post:

http://technoblot.wordpress.com/2006/09/08/winforms-causesvalidation-not-working-a-workaround/

A slightly less involved workaround.

Adam
So it seems that no easy workaround for this issue if I would like to stick to individual control validation. Obviously, to me, removing the X button is not a solution. But thank you very much for your suggestion.
Steve
All solutions will be workarounds, I happen to have found an easier alternative after a little searching - the answer has been amended to show this.
Adam