When validating Windows Forms, I find it rather akward to use multiple error providers. Therefore I decided to create an error log which automatically creates as many error providers as are required by the validation methods of a form. The class is listed at the end of this tip.
To use the class:
- Declare an error log member
private ErrorLog _eLog;
- Create an error log instance in the
load
or shown
events
eLog = new ErrorLog(this);
- Create a validation method which makes use of the error log
private bool IsDataOk() {
_eLog.Clear();
if (txtProjectName.Text == "") {
_eLog.AddError(txtProjectName, "Project name is obligatory");
}else if( Project.IsUnique(txtProjectName.Text ) == false){
_eLog.AddError(txtProjectName, "Project name must be unique");
}
if (txtPlannedDate.Text == ""){
_eLog.AddError(txtPlannedDate, "Planned date is obligatory");
}
return _eLog.IsOk();
}
The error log class follows:
public class ErrorLog {
ContainerControl _parent;
List _log;
List _controls;
public int Count {
get { return _log.Count; }
}
public string GetMessage(int idx) {
string result = "";
int itop = _log.Count;
if (idx <= itop) {
result = _log[idx].GetError(_controls[idx]);
}
return result;
}
public ErrorLog(ContainerControl parent) {
_parent = parent;
_log = new List();
_controls = new List();
}
public void Clear() {
_log.Clear();
_controls.Clear();
}
public void AddError(Control control, string message) {
ErrorProvider p = new ErrorProvider(_parent);
p.SetError(control, message);
_log.Add(p);
_controls.Add(control);
}
public bool IsOk(){
if (_log.Count == 0) {
return true;
} else {
return false;
}
}
}