65.9K
Home

An error log class to perform WinForms validations

Sep 22, 2011

CPOL
viewsIcon

17737

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:

  1. Declare an error log member
  2. private ErrorLog _eLog;
  3. Create an error log instance in the load or shown events
  4. eLog = new ErrorLog(this);
  5. Create a validation method which makes use of the error log
  6. 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;
      }
    }    
}