In this article I will explain with an example, how to validate TextBox in Windows Application (WinForms) using C# and VB.Net.
The validation of TextBox will be performed using the Validating event handler and the error message will be displayed using the ErrorProvider control in Windows Application (WinForms) using C# and VB.Net.
 
 
Adding ErrorProvider control to the Form
The ErrorProvider control is present in the Components Tab of the Visual Studio ToolBox.
Validate TextBox in Windows Application using C# and VB.Net
 
 
Form Design
The Form consists of a Label, a TextBox, a Button and an ErrorProvider control.
Validate TextBox in Windows Application using C# and VB.Net
 
 
Assigning Validating event handler to TextBox
The TextBox needs to be assigned Validating event handler.
Validate TextBox in Windows Application using C# and VB.Net
 
Inside the Validating event handler, the TextBox is validated for Empty and White space and if the validation fails i.e. if the TextBox is empty an error message is set in the ErrorProvider control.
C#
private void txtName_Validating(object sender, CancelEventArgs e)
{
    if (string.IsNullOrEmpty(txtName.Text.Trim()))
    {
        epName.SetError(txtName, "Name is required.");
    }
    else
    {
        epName.SetError(txtName, string.Empty);
    }
}
 
VB.Net
Private Sub txtName_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtName.Validating
    If String.IsNullOrEmpty(txtName.Text.Trim) Then
        epName.SetError(txtName, "Name is required.")
    Else
        epName.SetError(txtName, String.Empty)
    End If
End Sub
 
 
Screenshot
Validate TextBox in Windows Application using C# and VB.Net
 
 
Downloads