sekmet64
sekmet64

Reputation: 1665

What is the right method of validating .NET Windows Forms?

I'm searching on everywhere but just couldn't find a good example or text about this subject.

I would like to check for example the username and password validity when a user presses the OK button in a dialog.

Should I do this in the closing event, and cancel the dialog close if the validation fails? Or set the DialogResult to none instead of OK. These all seem kinda the wrong way to do it. I also saw the Validated and Validating events but aren't those for only validating a single control for valid input?

How can I check more controls together when the OK button is pressed, and cancel the form closing?

Upvotes: 2

Views: 1503

Answers (2)

Luke
Luke

Reputation: 11421

It depends on what you are trying to do. If you want to verify that the user entered something that could possibly be a valid username/password, you could use the Validating events (e.g. make sure it is long enough, etc). If you want to verify that the username/password corresponds to a valid account, then you have to wait until they hit the OK button and check the credentials. If they are bad then you can throw up a message box (or whatever) and prevent the dialog from closing (DialogResult.None).

Upvotes: 3

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

Each control offers Validating event. In this event you can implement validation of a single control. By default this validation is triggered when control lose focus. In contrast to Validated event, handler of this event receives CancelEventArgs so if validation fails you can cancel current operation (losing focus).

When you want to deal with complex validations you can set AutoValidate property of your form to AutoValidate.Disable. This will disable implicit validation (default behavior described before). Instead you will have to call ValidateChildren to trigger explicit validation of all child controls.

Upvotes: 1

Related Questions