我有多个 Control
元素(TextBox
es)附加到它们对应 ErrorProvider
的 s上。
我试图找到一种方法来countAllErrors(),甚至更好地处理EachError(),
所以这就是我想出的:
在课堂里:
internal TextBox email_textbox;
internal TextBox city_textbox;
internal TextBox address_textbox;
internal TextBox phone_textbox;
internal TextBox lastName_textbox;
internal TextBox firstName_textbox;
private ErrorProvider firstName_errPro;
private ErrorProvider lastName_errPro;
private ErrorProvider phone_errPro;
private ErrorProvider address_errPro;
private ErrorProvider city_errPro;
private ErrorProvider email_errPro;
internal Dictionary<ErrorProvider, Control> errors;
在表单的构造函数中:
errors = new Dictionary<ErrorProvider, Control>(6);
errors.Add( firstName_errPro ,firstName_textbox );
errors.Add( lastName_errPro ,lastName_textbox );
errors.Add( phone_errPro ,phone_textbox );
errors.Add( address_errPro ,address_textbox );
errors.Add( city_errPro ,city_textbox );
errors.Add( email_errPro ,email_textbox );
计算所有错误:
int countAllErrors()
{
int numOfErrors = errors.Count<KeyValuePair<ErrorProvider, Control>>(ep => ep.Key.GetError(ep.Value) != "");
return numOfErrors;
}
处理每个错误:
void handleEachError()
{
foreach (KeyValuePair<ErrorProvider, Control> errPair in errors.Where(ep => ep.Key.GetError(ep.Value) != ""))
{
ErrorProvider errorProvider = errPair.Key;
Control control = errPair.Value;
string errorStr = errorProvider.GetError(control);
// handle the error:
// for example - show it's text in a MessageBox:
MessageBox.Show(errorStr);
}
}
让我知道它是否有帮助.. ;)