How to use the Runtime Error Provider along with binding any control for validation
I am trying to create a validation in a reusable way.
Purpose: Make validation reusable.
The error provider must be associated with the managed passed dynamically and can be set or cleared at runtime.
When the user clicks on the OnClick event, all controls are checked using 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;
}
}
Question:
Every time the function is called, a new errorprovider object is created which I don't want. Each control should have at most 1 error provider and I should be able to search for it just like in asp.net to search for some control on the page.
How can i do this
a source to share
In most cases, you only really need one instance of ErrorProvider per form.
eg.
ErrorProvider errorProvider1 = new ErrorProvider();
or just drag it from the toolbar to the form.
When you call ErrorProvider, you provide a control and a message,
errorProvider1.SetError (dateTimePicker1, "HEY BAD DATE");
To clear the error ...
errorProvider1.SetError (dateTimePicker1, "");
So, one instance of ErrorProvider is all you really need in most situations.
a source to share
Do on PropertyOnDemand this way and access this property every time you need a 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;
}
}
a source to share