An error log class to perform WinForms validations





0/5 (0 vote)
Use an error log control to validate forms.
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
- Create an error log instance in the
load
orshown
events - Create a validation method which makes use of the error log
private ErrorLog _eLog;
eLog = new ErrorLog(this);
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");
}
//IMPORTANT : Notice each control must have its own if..elseif block
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;//Unnecesary : Kept only for a future error summary control
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;
}
}
}