Question

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?

Était-ce utile?

La 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, "");
        }
    }
}

Autres conseils

Move the construction of your ErrorProvider to the declaration line. So change:

private ErrorProvider errProvider;

to:

private ErrorProvider errProvider = new ErrorProvider(); 

and get rid of the initialization of that member that is currently in your SetError method.

It might also prove useful to show us how and when you are creating and storing a reference to the Error class instance you are using.

Also, putting your validation code inside of a method that is called SetError is a bit misleading (making your code harder to maintain). I'd name it something like ValidateControlHasValue or something like that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top