Windows Forms: Validation using Error Provider in C#

This post shows you How to use Error Provider in C# .NET Windows Forms Application to Display Error Icons for Form Validation.

Error Provider control that helps you validation data in c# winform.

To play the demo, you should create a new windows forms application project, next enter your project name is "ValidateDemo" and then click OK button.

Drag the TextBox, Label and Button from your visual studio toolbox to your winform, then design a simple UI login form as shown below.

error provider in c#

You need to add an ErrorProvider control to your windows form application. ErrorProvider presents a simple mechanism for indicating to the end user that a control on a form has an error associated with it.

If an error description string is specified for the control, an icon appears next to the control. Next, add the click event handler to the Login button as the following c# code.

private void btnLogin_Click(object sender, EventArgs e)
    if (ValidateChildren(ValidationConstraints.Enabled))
        MessageBox.Show(txtUsername.Text, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

Add the validating event handler to the TextBox allows you to check validate the TextBox control.

private void txtUsername_Validating(object sender, CancelEventArgs e)
    if (string.IsNullOrEmpty(txtUsername.Text))
        e.Cancel = true;
        //Show error
        errorProvider.SetError(txtUsername, "Please enter your user name !");
        e.Cancel = false;
        errorProvider.SetError(txtUsername, null);

Using c# errorprovider check if error through the Validating event handler. To clear error provider c# you can call the SetError method, then set value to null.

If you want to change icon errorprovider c#, you can add an imagelist control to your winform, then set icon to the error provider control as the following c# code.

this.errorProvider.Icon = Icon.FromHandle(((Bitmap)imageList.Images[0]).GetHicon());

You can also change the blink style to NeverBlink if you don't want to scare the user.

this.errorProvider.BlinkStyle = ErrorBlinkStyle.NeverBlink;