65.9K
CodeProject is changing. Read more.
Home

A Simple Extension for the ErrorProvider that Shows the Number of Errors

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Oct 26, 2020

CPOL
viewsIcon

3313

Simple class that uses composition to encapsulate the ErrorProvider and make available the number of errors

Introduction

This control encapsulates the C# ErrorProvider and exposes an ErrorCount property which is missing from the standard control.

Using the Code

First, create an instance of the control in the load or shown event:

        private void InterestForm_Shown(object sender, EventArgs e) {
            accepted = false;      
            epMain = new ErrorProviderExt(this);
        }

Then use it on the controls for validation:

        private void txtLowValue_Validating(object sender, CancelEventArgs e) {
            if (isValidValue(cbType.Text, txtLowValue.Text) == false) {
                epMain.SetError(txtLowValue, "invalid value");
            } else {
                epMain.ClearErrors(txtLowValue);
            }
        }

You can use the ErrorCount property to determine if the form contains any errors:

        private void btnOk_Click(object sender, EventArgs e) {
            if (epMain.ErrorCount == 0) {
                accept = true;
                Close();
            }
        }

The code for the control follows:

    public class ErrorProviderExt {
        private Dictionary<Control, string> _errorList = new Dictionary<Control, string>();
        private ErrorProvider provider = null;

        public ErrorProvider Provider { get { return provider; } }
        public int ErrorCount { get { return _errorList.Count; } }

        public ErrorProviderExt(Form f){
            provider = new ErrorProvider(f);
        }

        public void ClearErrors() {
            _errorList.Clear();
            provider.Clear();
        }

        public void ClearErrors(Control c) {
            if (_errorList.ContainsKey(c)) {
                _errorList.Remove(c);
                provider.SetError(c, null);
            }
        }

        public void SetError(Control c, string error) {
            if (error == null || String.IsNullOrWhiteSpace(error)) {
                ClearErrors(c);
            } else {
                if (_errorList.ContainsKey(c)) {
                    _errorList[c] = error;
                } else {
                    _errorList.Add(c, error);
                }
                provider.SetError(c, error);
            }
        }

        public bool HasError(Control c) {
            string error = null;
            if (_errorList.ContainsKey(c)) {
                error = _errorList[c];    
            }
            if (string.IsNullOrWhiteSpace(error)) {
                return false;
            } else {
                return true;
            }
        }               
    }
}

History

  • 26th October, 2020: Initial version