You have some useful features in windows forms to perform validation and show error messages including:
Using above options:
- You can perform validation when you are using data-binding to model classes.
- You van perform validation when you don't use data-binding.
- You can show error messages and an error icon near the controls which are in invalid states.
- You can decide to prevent the focus change from invalid controls or let the focus change.
- You can show a validation summary for your form.
- You can also apply DataAnnotations Validations in Windows Forms
IDataErrorInfo Interface
In cases which you have some model classes, the best fit for validation and providing error messages in windows forms is implementing IDataErrorInfo
. It's supported by data-binding mechanisms and some windows forms control like DataGridView
and ErrorProvider
.
To keep things simple you can write validation rules in your class and return error messages using IDataErrorInfo
properties. Even if you want to apply a more advanced scenario like using validation engines, at last it's better to implement IDataErrorInfo
to gain most consistency with widows forms.
You will use an ErrorProvider
to show error messages. It's enough to bind it to your data source and it shows errors automatically.
Validating Event of Controls
In cases that you don't have model classes and all validations should be done against controls, the best option is using Validating
event of controls. There you can set e.Cancel = true
to set the control state as invalid. Then you can prevent focus change or use the state of control in getting validation summary.
In this case you will use an ErrorProvider
to show errors. It's enough to set an error for a control in Validating
event this way: errorProvider1.SetError(control1, "Some Error")
or you can set an empty error message to remove validation error.
ErrorProvider Component
In both cases when you use databinding or when you use Validating
event, as mentioned above, ErrorProvider
shows and error icon with a tooltip that shows error message for you near the controls. (DataGridView
uses its own mechanism to show errors on rows and cells, without using an ErrorProvider
.)
You can also use the component to get a validation summary for your form using GetError
method of the component which return the error message of each control.
ValidateChildren Method and AutoValidate Property of Form
You can use ValidateChildren
method of form or your container control to check if there is a validation error for your controls or not.
Based on the value of AutoValidate
property of your form, it prevents focus change or let the focus change from invalid controls.