Using Error Provider Control in Windows Forms and C#

Introduction 

 
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 1: 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 2: Sample Form Layout 
 
Control Property Name Property Value
Label Text "Setup Driving Test Appointment"
Label Text "Name"
TextBox Text ""
Label Text "Age"
TextBox Text "" 
Label Text "Test Date"
DateTimePicker  Text "Create Appointment"
Button Text  
Table 1: Properties for Sample Form Layout Controls
 
Now add an 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.
  1. private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)  
  2. {  
  3.     ValidateName();  
  4. }  
  5. private bool ValidateName()  
  6. {  
  7.     bool bStatus = true;  
  8.     if (textBox1.Text == "")  
  9.     {  
  10.         errorProvider1.SetError(textBox1, "Please enter your Name");  
  11.         bStatus = false;  
  12.     }  
  13.     else  
  14.         errorProvider1.SetError(textBox1, "");  
  15.     return bStatus;  
  16. }  
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.
  1. private void textBox2_Validating(object sender, System.ComponentModel.CancelEventArgs e)  
  2. {  
  3.     ValidateAge();  
  4. }  
  5. private bool ValidateAge()  
  6. {  
  7.     bool bStatus = true;  
  8.     if (textBox2.Text == "")  
  9.     {  
  10.         errorProvider1.SetError(textBox2, "Please enter your Age");  
  11.         bStatus = false;  
  12.     }  
  13.     else  
  14.     {  
  15.         errorProvider1.SetError(textBox2, "");  
  16.         try  
  17.         {  
  18.             int temp = int.Parse(textBox2.Text);  
  19.             errorProvider1.SetError(textBox2, "");  
  20.             if (temp < 18)  
  21.             {  
  22.                 errorProvider1.SetError(textBox2, "You must be atleast 18 years old to setup a test");  
  23.                 bStatus = false;  
  24.             }  
  25.             else  
  26.             {  
  27.                 errorProvider1.SetError(textBox2, "");  
  28.             }  
  29.         }  
  30.         catch  
  31.         {  
  32.             errorProvider1.SetError(textBox2, "Please enter your age as a number");  
  33.             bStatus = false;  
  34.         }  
  35.     }  
  36.     return bStatus;  
  37. }
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 set up on weekdays only using validation on the form.
  1. private void dateTimePicker1_Validating(object sender, System.ComponentModel.CancelEventArgs e)  
  2. {  
  3.     ValidateTestDate();  
  4. }  
  5. private bool ValidateTestDate()  
  6. {  
  7.     bool bStatus = true;  
  8.     if ((dateTimePicker1.Value.DayOfWeek == DayOfWeek.Sunday) || dateTimePicker1.Value.DayOfWeek == DayOfWeek.Saturday))  
  9.     {  
  10.         errorProvider1.SetError(dateTimePicker1, "Appointment cannot be scheduled in the weekend. Please select a weekday");  
  11.         bStatus = false;  
  12.     }  
  13.     else  
  14.         errorProvider1.SetError(dateTimePicker1, "");  
  15.     return bStatus;  
  16. }  
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 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 fail 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.
  1. private void ValidateForm()  
  2. {  
  3.     bool bValidName = ValidateName();  
  4.     bool bValidAge = ValidateAge();  
  5.     bool bValidTestDate = ValidateTestDate();  
  6.     if (bValidName && bValidAge && bValidTestDate)  
  7.         MessageBox.Show("Appointment will be created now");  
  8.     else  
  9.         MessageBox.Show("Please enter valid data");  
  10. }
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 3: Validation Form
 
 
Figure 4: Validation Errors
 
 
Figure 5: Error message displayed in addition to the form error indicators.
 
Complete Code Listing: Save as ValidatingForm.cs
  1. using System;  
  2. using System.Drawing;  
  3. using System.Collections;  
  4. using System.ComponentModel;  
  5. using System.Windows.Forms;  
  6. using System.Data;  
  7. namespace SampleApp  
  8. {  
  9.     public class Form1 : System.Windows.Forms.Form  
  10.     {  
  11.         private System.Windows.Forms.Label label1;  
  12.         private System.Windows.Forms.TextBox textBox1;  
  13.         private System.Windows.Forms.TextBox textBox2;  
  14.         private System.Windows.Forms.Label label2;  
  15.         private System.Windows.Forms.Label label3;  
  16.         private System.Windows.Forms.DateTimePicker dateTimePicker1;  
  17.         private System.Windows.Forms.Label label4;  
  18.         private System.Windows.Forms.Button button1;  
  19.         private System.Windows.Forms.ErrorProvider errorProvider1;  
  20.         public Form1()  
  21.         {  
  22.             this.label1 = new System.Windows.Forms.Label();  
  23.             this.textBox1 = new System.Windows.Forms.TextBox();  
  24.             this.textBox2 = new System.Windows.Forms.TextBox();  
  25.             this.label2 = new System.Windows.Forms.Label();  
  26.             this.label3 = new System.Windows.Forms.Label();  
  27.             this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();  
  28.             this.label4 = new System.Windows.Forms.Label();  
  29.             this.button1 = new System.Windows.Forms.Button();  
  30.             this.errorProvider1 = new System.Windows.Forms.ErrorProvider();  
  31.             this.SuspendLayout();  
  32.             this.label1.Location = new System.Drawing.Point(8, 40);  
  33.             this.label1.Name = "label1";  
  34.             this.label1.Size = new System.Drawing.Size(80, 16);  
  35.             this.label1.TabIndex = 0;  
  36.             this.label1.Text = "Name";  
  37.             this.label1.Click += new System.EventHandler(this.label1_Click);  
  38.             this.textBox1.Location = new System.Drawing.Point(96, 40);  
  39.             this.textBox1.Name = "textBox1";  
  40.             this.textBox1.Size = new System.Drawing.Size(104, 20);  
  41.             this.textBox1.TabIndex = 1;  
  42.             this.textBox1.Text = "";  
  43.             this.textBox1.Validating += new System.ComponentModel.CancelEventHandler this.textBox1_Validating);  
  44.             this.label2.Location = new System.Drawing.Point(8, 64);  
  45.             this.label2.Name = "label2";  
  46.             this.label2.Size = new System.Drawing.Size(80, 16);  
  47.             this.label2.TabIndex = 3;  
  48.             this.label2.Text = "Age";  
  49.             this.textBox2.Location = new System.Drawing.Point(96, 64);  
  50.             this.textBox2.Name = "textBox2";  
  51.             this.textBox2.Size = new System.Drawing.Size(104, 20);  
  52.             this.textBox2.TabIndex = 4;  
  53.             this.textBox2.Text = "";  
  54.             this.textBox2.Validating += new System.ComponentModel.CancelEventHandler this.textBox2_Validating);  
  55.             this.label3.Location = new System.Drawing.Point(8, 88);  
  56.             this.label3.Name = "label3";  
  57.             this.label3.Size = new System.Drawing.Size(80, 16);  
  58.             this.label3.TabIndex = 5;  
  59.             this.label3.Text = "Test Date";  
  60.             this.dateTimePicker1.Location = new System.Drawing.Point(96, 88);  
  61.             this.dateTimePicker1.Name = "dateTimePicker1";  
  62.             this.dateTimePicker1.TabIndex = 6;  
  63.             this.dateTimePicker1.Validating += new System.ComponentModel.CancelEventHandler(this.dateTimePicker1_Validating);  
  64.             this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold,  
  65.             System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));  
  66.             this.label4.Location = new System.Drawing.Point(16, 8);  
  67.             this.label4.Name = "label4";  
  68.             this.label4.Size = new System.Drawing.Size(184, 23);  
  69.             this.label4.TabIndex = 7;  
  70.             this.label4.Text = "Setup Driving Test Appointment";  
  71.             this.button1.Location = new System.Drawing.Point(80, 128);  
  72.             this.button1.Name = "button1";  
  73.             this.button1.Size = new System.Drawing.Size(120, 23);  
  74.             this.button1.TabIndex = 8;  
  75.             this.button1.Text = "Create Appointment";  
  76.             this.button1.Click += new System.EventHandler(this.button1_Click);  
  77.             this.errorProvider1.DataMember = null;  
  78.             this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);  
  79.             this.ClientSize = new System.Drawing.Size(320, 173);  
  80.             this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button1, this.label4, this.dateTimePicker1, this.label3, this.label2, this.textBox2, this.textBox1, this.label1 });  
  81.             this.Name = "Form1";  
  82.             this.Text = "Form1";  
  83.             this.Load += new System.EventHandler(this.Form1_Load);  
  84.             this.ResumeLayout(false);  
  85.         }  
  86.         [STAThread]  
  87.         static void Main()  
  88.         {  
  89.             Application.Run(new Form1());  
  90.         }  
  91.         private void label1_Click(object sender, System.EventArgs e)  
  92.         {  
  93.         }  
  94.         private void Form1_Load(object sender, System.EventArgs e)  
  95.         {  
  96.             errorProvider1.ContainerControl = this;  
  97.         }  
  98.         private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)  
  99.         {  
  100.             ValidateName();  
  101.         }  
  102.         private void textBox2_Validating(object sender, System.ComponentModel.CancelEventArgs e)  
  103.         {  
  104.             ValidateAge();  
  105.         }  
  106.         private void dateTimePicker1_Validating(object sender, System.ComponentModel.CancelEventArgs e)  
  107.         {  
  108.             ValidateTestDate();  
  109.         }  
  110.         private void button1_Click(object sender, System.EventArgs e)  
  111.         {  
  112.             ValidateForm();  
  113.         }  
  114.         private void ValidateForm()  
  115.         {  
  116.             bool bValidName = ValidateName();  
  117.             bool bValidAge = ValidateAge();  
  118.             bool bValidTestDate = ValidateTestDate();  
  119.             if (bValidName && bValidAge && bValidTestDate)  
  120.                 MessageBox.Show("Appointment will be created now");  
  121.             else  
  122.                 MessageBox.Show("Please enter valid data");  
  123.         }  
  124.         private bool ValidateName()  
  125.         {  
  126.             bool bStatus = true;  
  127.             if (textBox1.Text == "")  
  128.             {  
  129.                 errorProvider1.SetError(textBox1, "Please enter your Name");  
  130.                 bStatus = false;  
  131.             }  
  132.             else  
  133.                 errorProvider1.SetError(textBox1, "");  
  134.             return bStatus;  
  135.         }  
  136.         private bool ValidateAge()  
  137.         {  
  138.             bool bStatus = true;  
  139.             if (textBox2.Text == "")  
  140.             {  
  141.                 errorProvider1.SetError(textBox2, "Please enter your Age");  
  142.                 bStatus = false;  
  143.             }  
  144.             else  
  145.             {  
  146.                 errorProvider1.SetError(textBox2, "");  
  147.                 try  
  148.                 {  
  149.                     int temp = int.Parse(textBox2.Text);  
  150.                     errorProvider1.SetError(textBox2, "");  
  151.                     if (temp < 18)  
  152.                     {  
  153.                         errorProvider1.SetError(textBox2, "You must be atleast 18 years old to setup a test");  
  154.                         bStatus = false;  
  155.                     }  
  156.                     else  
  157.                     {  
  158.                         errorProvider1.SetError(textBox2, "");  
  159.                     }  
  160.                 }  
  161.                 catch  
  162.                 {  
  163.                     errorProvider1.SetError(textBox2, "Please enter your age as a number");  
  164.                     bStatus = false;  
  165.                 }  
  166.             }  
  167.             return bStatus;  
  168.         }  
  169.         private bool ValidateTestDate()  
  170.         {  
  171.             bool bStatus = true;  
  172.             if ((dateTimePicker1.Value.DayOfWeek == DayOfWeek.Sunday) ||  
  173.             (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Saturday))  
  174.             {  
  175.                 errorProvider1.SetError(dateTimePicker1, "Appointment cannot be scheduled in the weekend. Please select a weekday");  
  176.                 bStatus = false;  
  177.             }  
  178.             else  
  179.                 errorProvider1.SetError(dateTimePicker1, "");  
  180.             return bStatus;  
  181.         }  
  182.     }  
  183. }  
NOTE: This article is purely for demonstration. This article should not be construed as the best practices white paper. This article is entirely original, unless specified. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof.
 

Conclusion

 
In this example, we learned how to invoke validate input to Windows Forms controls and display user-friendly informative error messages.


Similar Articles