Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

An error log class to perform WinForms validations

0.00/5 (No votes)
22 Sep 2011 1  
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. C#
    private ErrorLog _eLog;

  3. Create an error log instance in the load or shown events
  4. C#
    eLog = new ErrorLog(this);

  5. Create a validation method which makes use of the error log
  6. C#
    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:


C#
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;
      }
    }    
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here