In this article I will explain with an example, how to use ErrorProvider control in Windows Forms (WinForms) Application using C# and VB.Net.
What is ErrorProvider?
The ErrorProvider control is used to display an alert (an icon with message) to the user, when controls on the Form has error associated with it.
When the mouse hovers over the icon, a ToolTip appears showing the Error Message only if an error description string (message) is specified for the control.
The ErrorProvider control is present in the Components Tab of the Visual Studio ToolBox as shown below.
The ErrorProvider control has many properties, some of them are as following.
1. Icon - Gets or sets the Icon which will be displayed next to a control.
2. BlinkRate - Gets or sets the rate at which the error icon flashes. It is measured in milliseconds.
The ErrorProvider has following methods.
1. SetError - Sets the error description string for the specified control. The message will be displayed Tooltip.
2. Clear - Clears all settings associated with this component.
Note: For more details about
ErrorProvider, please refer
MSDN.
Form Design
The Form consists of following controls:
Label – For labelling TextBox.
Implementing ErrorProvider control
TextBox – For capturing user input.
The TextBox has been assigned with the Validating event handler.
Button – For submitting the Form.
Error Provider – For displaying Error Message with icon.
Namespaces
You will need to import the following namespaces
C#
using System.ComponentModel;
VB.Net
Imports System.ComponentModel
Validating TextBox in C# and VB.Net
When the Button is clicked, the Validating event handler of TextBox is executed.
Validating
Inside this event handler, a check is performed whether the TextBox is empty or not.
If found empty or NULL, then Error Provider message is set to empty else the Error Message is displayed with icon.
C#
private void txtName_Validating(object sender, CancelEventArgs e)
{
if (!string.IsNullOrEmpty(txtName.Text.Trim()))
{
epName.SetError(txtName, string.Empty);
}
else
{
epName.SetError(txtName, "Name is required.");
}
}
VB.Net
Private Sub txtName_Validating(sender As Object, e As CancelEventArgs) Handles txtName.Validating
If Not String.IsNullOrEmpty(txtName.Text.Trim) Then
epName.SetError(txtName, String.Empty)
Else
epName.SetError(txtName, "Name is required.")
End If
End Sub
Screenshot
Downloads