Search code examples
c#winformserrorprovider

ErrorProvider using class


I have made the following class to avoid the repetition if else code , again and again :

public class Error 
{

    private ErrorProvider errProvider;


    public void SetError(Control control, string value)
    {

        errProvider = new ErrorProvider();

        if (control.Text.Trim().Length == 0)
        {
            errProvider.SetError(control, value);
        }
        else
        {
            errProvider.SetError(control, "");

        }

    }


}

and validation on textbox code is

private void textBox1_Validating(object sender, CancelEventArgs e)
    {

            erp.SetError(textBox1, "Please Enter Name");

    }
  1. After typing the text in texbox, as I press enter, it working fine;
  2. Without Entering any thing in textbox, as I press Enter , it also working fine means Waring red icon appears; BUT
  3. after warning, as I press tab after entering text in textbox , warning Icon does not disappear , it sould be removed.

without class it is working fine with the same code

update?


Solution

  • Use Field Initializer

    private readonly ErrorProvider errProvider = new ErrorProvider();
    

    You should use Field Initializer for errProvider, because every time calling Error.SetError, ErrorProvider will be constructed, and a constructed ErrorProvider will not only no disappear but also be just layered.


    [updated]

    public class Error
    {
        private readonly ErrorProvider errProvider = new ErrorProvider();
        public void SetError(Control control, string value)
        {
    
            if (control.Text.Trim().Length == 0)
            {
                errProvider.SetError(control, value);
            }
            else
            {
                errProvider.SetError(control, "");
            }
        }
    }