In this article I will explain with an example, how to make TextBox required in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The Form consists of a Label, a TextBox, two ErrorProvider controls i.e. one for displaying error message and one for displaying success message and a Button control.
Inside the Properties window, the Icon for ErrorProvider i.e. epSuccess has been set with a tick mark icon in the Icon property.
Validating TextBox on Button Click
Inside the Properties window, the TextBox is assigned with Validating event handler as shown below.
Inside this Validating event handler, the TextBox is validated for empty (blank) and white space and if the validation fails i.e. if the TextBox is empty (blank) an error message is set in the ErrorProvider control (epError) which will make the error icon visible.
And if the TextBox is not empty i.e. if it has valid value, then the ErrorProvider control (epError) is set with a blank error message which will hide the error icon.
C#
private void txtName_Validating(object sender, CancelEventArgs e)
{
if (!string.IsNullOrEmpty(txtName.Text.Trim()))
{
epError.SetError(txtName, string.Empty);
}
else
{
epError.SetError(txtName, "Name is required.");
}
}
VB.Net
Private Sub txtName_Validating(sender As Object , e As System.ComponentModel.CancelEventArgs) Handles txtName.Validating
If Not String.IsNullOrEmpty(txtName.Text.Trim) Then
epError.SetError(txtName, String.Empty)
Else
epError.SetError(txtName, "Name is required.")
End If
End Sub
Displaying Success Icon when the TextBox is filled
Inside the Properties window, the TextBox is assigned with KeyUp event handler as shown below.
Inside this KeyUp event handler, in the very first line, the ErrorProvider control (epError) is set with an empty error message so that the error icon is hidden.
And then, a check is made whether the TextBox is empty (blank) or not, if the TextBox has value then, the ErrorProvider control (epSuccess) is set with the success message which displays the check icon.
C#
private void txtName_KeyUp(object sender, KeyEventArgs e)
{
epError.SetError(txtName, string.Empty);
if (!string.IsNullOrEmpty(txtName.Text.Trim()))
{
epSuccess.SetError(txtName, "Valid");
}
else
{
epSuccess.SetError(txtName, string.Empty);
}
}
VB.Net
Private Sub txtName_KeyUp(sender As Object, e As KeyEventArgs) Handles txtName.KeyUp
epError.SetError(txtName, String.Empty)
If Not String.IsNullOrEmpty(txtName.Text.Trim) Then
epSuccess.SetError(txtName, "Valid")
Else
epSuccess.SetError(txtName, String.Empty)
End If
End Sub
Screenshot
Downloads