Introduction
Have you ever found it annoying when you keep getting the error message box for invalid inputs on Windows Forms. Now the days are gone when we can use the ErrorProvider component class from .NET 2.0 which allows you to validate the forms without any message box. Instead, an error icon blinks where the error has occurred.
ErrorProvider Component Overview
The Windows Forms ErrorProvider component is used to validate user input on a form or control. It is typically used in conjunction with validating user input on a form, or displaying errors within a dataset. An error provider is a better alternative than displaying an error message in a message box, because once a message box is dismissed, the error message is no longer visible. This component displays an error icon next to the relevant control, such as a textbox; when the user positions the mouse pointer over the error icon, a ToolTip appears, showing the error message string.
Using the Component
To use this component, you need to drag and drop the ErrorProvider component from the toolbox or add the control at runtime:
Private Num_ErrorProviders As New ErrorProvider()
Private Null_ErrorProviders As New ErrorProvider()
Private WithEvents Num_Textbox As New TextBox
Private WithEvents Null_Textbox As New TextBox
Once the component is placed or created at runtime, we need to validate a control. For that, we will take two textbox controls, one to validate whether the input of the textbox is numeric or not and the other to validate whether the textbox is empty or null.
To validate a textbox, you need to use the SetError method of the ErrorProvider class:
Num_ErrorProviders.SetError(Num_Textbox, "Not a numeric value.")
To do so, you need to use the validating event or validated event of the textbox. The difference between these two is that the validated event is fired when the textbox loses its focus and it's that point of time when the textbox gets validated. Now let's see how we use it to do validation:
Private Sub Num_Textbox_Validating(ByVal Sender As Object, _
ByVal e As System.EventArgs) Handles Num_Textbox.Validating
If Not IsNumeric(Num_Textbox.Text) Then
Num_ErrorProviders.SetError(Num_Textbox, "Not a numeric value.")
Else
Num_ErrorProviders.SetError(Num_TextBox, "")
End If
End Sub
Private Sub Null_Textbox_Validated(ByVal Sender As Object, _
ByVal e As System.EventArgs) Handles Null_Textbox.Validated
If String.IsNullOrEmpty(Null_Textbox.Text) Then
Null_ErrorProviders.SetError(Null_Textbox, "Textbox is Empty.")
Else
Null_ErrorProviders.SetError(Null_TextBox, "")
End If
End Sub
If any validating is done, a blink icon will appear next to the textbox.
Points of Interest
You use this control in such a way that you can get the valid data from the user.
History
- 23rd February, 2008: Initial post