Reputation: 21108
I am trying to create a Validation in a reusable fashion.
Purpose: Make the validation control reusable.
Error Provider should associate with control passed dynamically and can be set or cleared at run time.
When user press OnClick event then all the controls gets validated with their own Error Providers.
public bool IsFieldEmpty(ref TextBox txtControl, Boolean SetErrorProvider,string msgToShowOnError)
{
ErrorProvider EP = new ErrorProvider();
if (txtControl.Text == string.Empty)
{
if(SetErrorProvider==true)
EP.SetError(txtControl, msgToShowOnError);
return true;
}
else
{
if(SetErrorProvider==true)
EP.Clear();
return false;
}
}
Issue:
Every time the function is called new errorprovider object gets created which i dont want. Every control should not have more than 1 error provider and i should be able to search it just like as done in asp.net to search for some control on a Page.
How can I do this
Upvotes: 2
Views: 7142
Reputation: 3834
Make on PropertyOnDemand like this and access that property every time u need new ErrorProvider
private ErrorProvider _ErrorProvider = null;
//PropertyOnDemand
private ErrorProvider ErrorProviders
{
get
{
if (_ErrorProvider == null)
{
_ErrorProvider = new ErrorProvider();
return _ErrorProvider;
}
else
return _ErrorProvider;
}
}
public bool IsFieldEmpty(ref TextBox txtControl, Boolean SetErrorProvider, string msgToShowOnError)
{
if (txtControl.Text == string.Empty)
{
if (SetErrorProvider == true)
ErrorProviders.SetError(txtControl, msgToShowOnError);
return true;
}
else
{
if (SetErrorProvider == true)
ErrorProviders.Clear();
return false;
}
}
Upvotes: 0
Reputation: 37104
In most cases you really only need one instance of ErrorProvider on a form.
E.g.
ErrorProvider errorProvider1 = new ErrorProvider();
or just drag one from the toolbox onto the form.
When calling an ErrorProvider, you supply the control and the message,,
errorProvider1.SetError (dateTimePicker1, "HEY BAD DATE");
To clear the error...
errorProvider1.SetError (dateTimePicker1, "");
So, one ErrorProvider instance is all you really need in most situations.
Upvotes: 3