Error Provider Control

The ErrorProvider component of Windows Forms is used to validate user input on a form or check. It is typically used to validate user input on a form, or to display errors in a dataset. An error provider is a better alternative to displaying an error message in a Message Box, as the error message will no longer be visible once a message box is dismissed.

Error Provider Control UK Academe

The ErrorProvider component displays an error icon next to the relevant control, such as a text box ; a ToolTip shows the error message string when the user positions the mouse pointer over the error icon.


private void txtFirstName_Validating(object sender, CancelEventArgs e)
        {
            if(IsFirstNameVaild())
            {
                errorProvider.SetError(txtFirstName, String.Empty);
            }
            else
            {
                errorProvider.SetError(txtFirstName, "First name is required.");
            }
        }

Create Is Validating Method


 private bool IsFirstNameVaild()
        {
            return txtFirstName.Text.Length > 0;
        }

The SetError method is called with or without appropriate error text during a control's Validated event, depending upon the content in the control.

Complete Source Code


using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace ErrorProviderControl
{
    public partial class frmErrorProvider : Form
    {
        public frmErrorProvider()
        {
            InitializeComponent();
        }

        private bool IsFirstNameVaild()
        {
            return txtFirstName.Text.Length > 0;
        }
        private bool IsLastNameVaild()
        {
            return txtLastName.Text.Length > 0;
        }

        private void txtFirstName_Validating(object sender, CancelEventArgs e)
        {
            if(IsFirstNameVaild())
            {
                errorProvider.SetError(txtFirstName, String.Empty);
            }
            else
            {
                errorProvider.SetError(txtFirstName, "First name is required.");
            }
        }

        private void txtLastName_Validating(object sender, CancelEventArgs e)
        {
            if (IsLastNameVaild())
            {
                errorProvider.SetError(txtLastName, String.Empty);
            }
            else
            {
                errorProvider.SetError(txtLastName, "Last name is required.");
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if(IsFormValid())
            MessageBox.Show(txtFirstName.Text + " " + txtLastName.Text, "Information"); 
        }

        private bool IsFormValid()
        {
            foreach (Control ctrl in errorProvider.ContainerControl.Controls)
                if (errorProvider.GetError(ctrl) != String.Empty)
                    return false;
            return true;
        }
    }
}

Error Provider Control Source Code

Video Tutorial