简体   繁体   中英

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

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.

错误提供程序正确显示错误

但是当我输入有效输入时,错误图标不会消失。

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);
        }
    }

https://docs.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM