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");
}
without class it is working fine with the same code
update?
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, "");
}
}
}