Error Provider is not clearing itself even if the inputs are valid

723 Views Asked by At

I am using Windows Forms and Error Provider to validate my Textbox, the validation works as it intended but even if the input matches the validation, the Error Provider wont clear itself.

Here are some screenshots on the issue.

The error provider shows the error correctly

But when i enter the valid input, the error icon wont disappear.

Here is my code, please advice me on how to fix it.

private void usernamet_Validating(object sender, CancelEventArgs e)
    {
        int username = usernamet.Text.Length;

        ErrorProvider errorProvider = new ErrorProvider();
        if (string.IsNullOrEmpty(usernamet.Text))
        {
            
            e.Cancel = true;
            usernamet.Focus();
            errorProvider.SetError(usernamet, "Username cannot be empty");
        }
        else if (username < 5 || username >= 20 )
        {
            e.Cancel = true;
            usernamet.Focus();
            errorProvider.SetError(usernamet, "Username must have more than 5 characters and less than 20 characters.");
        }
        else if (!Regex.IsMatch(usernamet.Text, @"^[a-zA-Z0-9@.]*$"))
        {
            e.Cancel = true;
            usernamet.Focus();
            errorProvider.SetError(usernamet, "Username cannot contain special characters.");
        }
        else
        {
            e.Cancel = false;
            errorProvider.Clear();
            errorProvider.SetError(usernamet, null);
        }
    }
1

There are 1 best solutions below

6
Reza Faghani On

https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.errorprovider.clear?view=netframework-4.7.2

Calling this method clears all property settings for this ErrorProvider, restoring the properties to their default values. To clear the error message, call the SetError method and pass in Empty for the String value. This removes the error glyph from the specified Control.