C# – Validating Data In A WinForm

cnetwinforms

I have created a dialog box in my WinForms application. This has many text boxes and ok/cancel buttons. When the user clicks ok, I only want the dialog box to close if all entries are valid. I can see how to do this with the "Validating" events for each control separately. That is fine. But these only seem to fire when a control loses focus. However, empty text boxes in my dialog are also invalid input which means the user may never have focused on that control. I would prefer to just validate all controls on clicking OK.

I can't work out how to do this though. Overriding the onclick of the OK button doesn't seem to have an option for stopping the window from closing. The Form IsClosing event does by setting Cancel = true. But this doesn't seem to be able to distinguish between whether the OK or Cancel button is clicked. Obviously if the cancel button is clicked I don't care about validation and want to allow the form to close regardless.

What is the best approach for doing this?]

Update:
I already had CausesValidation set to true on both my form and ok button but my validation event does not get fired when I click the ok button. I mention this as it was suggested as a solution below.

Best Answer

Please select the form > Set the property CausesValidation to true

Select OK button and again set property CausesValidation to true

and then it will take care of all the validations.

Important points: 1) You must mention e.Cancel=true in all the validating eventhandlers

2) If your buttons are in panels then you must set panels (or any parent control's) CausesValidation property to true

Edit:

3) Validate fires just before loss of focus. While pressing Enter will cause the default button to Click, it doesn't move the focus to that button, hence no validation event will be fired if you have set forms AcceptButton Property to OK button