Quantcast

Using Error Provider Control in Windows Forms and C#

Get the WebProNews Newsletter:
[ Business]

In this example we will see how to use the ErrorProvider control in Windows forms to provide validations in Windows Forms and display user-friendly error messages to the user if the validation fails.

Figure : Error Provider Sample

The complete code listing is provided at the end of the sample.

Create a new Visual C# Windows Forms application. The project will create a default form Form1.cs. Add controls as shown in the figure below and set the properties of the controls as indicated in the table.

Figure : Sample Form Layout

Table : Properties for Sample Form Layout Controls

Now add a ErrorProvider control to the Form. In Visual Studio.Net, you can drag and drop the control from the toolbox. The control is added to the form and displayed in the control tray in the Windows form in Design view. If you are not using Visual Studio.Net, then you can add the control in the code. Please refer to the code listing provided at the end of the article.

Now create an event handler for the “Validating” event of the textBox1 control. We will validate the TextBox to ensure that the user has entered a value.

Code Snippet: Validate the Name TextBox

Next we will add the validations for the textBox2 control which accepts Age as the data input. We will ensure that the Age is mandatory, is in numeric format and the user is 18 years or older.

Code Snippet: Validate the Age TextBox

Now we will add the validations for the DateTimePicker controls which collects the Test Date information. We will implement the business rule to allow test appointments to be setup on weekdays only using validation on the form.

Code Snippet: Validate the Date Selection

Invoking the SetError method of the ErrorProvider control displays an error indicator image next to the control specified as the first argument to the the SetError method. The string specified in the second argument in the function invocation is displayed as the tooltip when the mouse is moved over the Error indicator.

When the user enters data in the controls which fails validation, a blinking error image is displayed on the form next to the control and the error message is displayed as a tooltip to the error image.

You can display multiple error indications on a form at the same time using the same ErrorProvider control. You can also display errors that occur in DataSets. You need to set the DataSource, DataMember and ContainerControl properties of the ErrorProvider control to set the error for a databound control. To display the dataset column error, invoke the SetColumnError method of the ErrorProvider.
You can customize the ErrorProvider control to set the BlinkRate and BlinkStyle. You can also display a custom error image instead of the default image.

Now we will add code in our sample to validate the complete form when the “Create Appointment” button is clicked.

Code Snippet : Validate all form controls when the Create Appointment button is clicked.

If the user clicks the Create Appointment button and the data is not valid, error indicators are displayed next to the controls with invalid data.

Validation in Action

Figure: Validation Form

Figure : Validation Errors

Figure : Error message displayed in addition to the form error indicators.

Complete Code Listing

Save as ValidatingForm.cs

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace SampleApp
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.DateTimePicker dateTimePicker1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ErrorProvider errorProvider1;

public Form1()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
this.label4 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.errorProvider1 = new System.Windows.Forms.ErrorProvider();

this.SuspendLayout();

this.label1.Location = new System.Drawing.Point(8, 40);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Name";
this.label1.Click += new System.EventHandler(this.label1_Click);

this.textBox1.Location = new System.Drawing.Point(96, 40);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(104, 20);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "";
this.textBox1.Validating += new System.ComponentModel.CancelEventHandler(this.textBox1_Validating);

this.label2.Location = new System.Drawing.Point(8, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Age";

this.textBox2.Location = new System.Drawing.Point(96, 64);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(104, 20);
this.textBox2.TabIndex = 4;
this.textBox2.Text = "";
this.textBox2.Validating += new System.ComponentModel.CancelEventHandler(this.textBox2_Validating);

this.label3.Location = new System.Drawing.Point(8, 88);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 16);
this.label3.TabIndex = 5;
this.label3.Text = "Test Date";

this.dateTimePicker1.Location = new System.Drawing.Point(96, 88);
this.dateTimePicker1.Name = "dateTimePicker1";
this.dateTimePicker1.TabIndex = 6;
this.dateTimePicker1.Validating += new System.ComponentModel.CancelEventHandler(this.dateTimePicker1_Validating);

this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold,

System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label4.Location = new System.Drawing.Point(16, 8);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(184, 23);
this.label4.TabIndex = 7;
this.label4.Text = "Setup Driving Test Appointment";

this.button1.Location = new System.Drawing.Point(80, 128);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(120, 23);
this.button1.TabIndex = 8;
this.button1.Text = "Create Appointment";
this.button1.Click += new System.EventHandler(this.button1_Click);

this.errorProvider1.DataMember = null;

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(320, 173);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.button1, this.label4, this.dateTimePicker1, this.label3,

this.label2, this.textBox2, this.textBox1, this.label1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void label1_Click(object sender, System.EventArgs e)
{

}

private void Form1_Load(object sender, System.EventArgs e)
{
errorProvider1.ContainerControl = this;
}

private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
ValidateName();
}

private void textBox2_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
ValidateAge();
}

private void dateTimePicker1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
ValidateTestDate();
}

private void button1_Click(object sender, System.EventArgs e)
{
ValidateForm();
}

private void ValidateForm( )
{
bool bValidName = ValidateName();
bool bValidAge = ValidateAge();
bool bValidTestDate = ValidateTestDate();
if (bValidName && bValidAge && bValidTestDate )
MessageBox.Show("Appointment will be created now");
else
MessageBox.Show("Please enter valid data");
}

private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == "")
{
errorProvider1.SetError (textBox1,"Please enter your Name");
bStatus = false;
}
else
errorProvider1.SetError (textBox1,"");
return bStatus;
}

private bool ValidateAge()
{
bool bStatus = true;
if (textBox2.Text == "")
{
errorProvider1.SetError (textBox2,"Please enter your Age");
bStatus = false;
}
else
{
errorProvider1.SetError (textBox2,"");
try
{
int temp = int.Parse(textBox2.Text);
errorProvider1.SetError (textBox2,"");
if (temp < 18)
{
errorProvider1.SetError (textBox2,"You must be atleast 18 years old to setup a test");
bStatus = false;
}
else
{
errorProvider1.SetError (textBox2,"");
}
}
catch
{
errorProvider1.SetError (textBox2,"Please enter your age as a number");
bStatus = false;
}
}
return bStatus;
}

private bool ValidateTestDate()
{
bool bStatus = true;
if ((dateTimePicker1.Value.DayOfWeek ==DayOfWeek.Sunday) || (dateTimePicker1.Value.DayOfWeek ==DayOfWeek.Saturday))
{
errorProvider1.SetError (dateTimePicker1, "Appointment cannot be scheduled in the weekend. Please select a weekday");
bStatus = false;
}
else
errorProvider1.SetError (dateTimePicker1, "");
return bStatus;
}
}
}

Dipal Choksi is a Bachelor of Engineering (Computer Science). She has industry experience in team-effort projects and also as an individual contributor. She has worked on Visual Basic, Visual C++, Java, Directory Services, ASP projects

Using Error Provider Control in Windows Forms and C#
About Dipal Choksi
Dipal Choksi is a Bachelor of Engineering (Computer Science). She has industry experience in team-effort projects and also as an individual contributor. She has worked on Visual Basic, Visual C++, Java, Directory Services, ASP projects WebProNews Writer
Top Rated White Papers and Resources
  • RAGHU PRAKASH MARUVADA

    hai i want code