However, I prefer to call it explicitly and handle all validation at once since you most likely will take action only if the entire control’s children pass validation. The most important thing to recognize here is how precise you can be with the validation error message in the error provider.There are 2 code paths for validation failure, and in each case we provide the user with an appropriate error message.First, add the following code to the Form’s constructor after the Initialize Component method: This is a handy trick to prevent implicit validation of our controls when they lose focus.You do not have to disable the Form’s Auto Validate property.The error provider simply takes a control and a message in the Set Error method and does the rest of the work for you!If the user enters invalid data they’ll see an icon shown in Figure 3.
Let’s assume when we click our save button that we wish to validate the controls and display an icon if there is a problem.
After the validating event returns without being cancelled, meaning we have valid user input, then the validated event will be raised.
As a follow up to my previous post about enhancing the validation controls within Windows Forms, there might be times when you would like to manually invoke the “Validating” event of a control.
For example, you might want to have a routine that fires on the form's “Closing” event or a data save method to loop through all the controls on your form and validate them independently to ensure that all controls are valid.
This might be a common scenario in data entry forms where you might create a new record and the user might not touch all the fields on your form (and thus never trigger the “Validating” event of your controls). One, pointed out by Chris Sells (read more), invokes the Control's “Notify Validating” event through Reflection.Here is an example: You can also trigger the Validation event by giving focus to a control and taking the focus away.