Windows Forms: Validation using Error Provider in C#

Display Error Icons for Form Validation using Error Provider control in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ValidateDemo" and then click OK

c# errorproviderStep 2: Design your form as below

error provider in c#

You need to add an ErrorProvider control to your windows form application. ErrorProvider presents a simple mechanism for indicating to the end user that a control on a form has an error associated with it. If an error description string is specified for the control, an icon appears next to the control.

Step 3: Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ValidateDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (ValidateChildren(ValidationConstraints.Enabled))
            {
                MessageBox.Show(txtUsername.Text, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void txtUsername_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsername.Text))
            {
                e.Cancel = true;
                txtUsername.Focus();
                //Show error
                errorProvider.SetError(txtUsername, "Please enter your user name !");
            }
            else
            {
                e.Cancel = false;
                errorProvider.SetError(txtUsername, null);
            }
        }
    }
}

VIDEO TUTORIALS