Search

Using Error Provider Control in Windows Forms and C#

0 views

Preparing the Windows Form and Placing Controls

Begin by launching Visual Studio and creating a new C# Windows Forms Application. The project template automatically adds a form called Form1, which appears in the designer. Your first task is to arrange the user interface that will collect the data for a driving‑test appointment. Think of the form as a checklist: name, age, and test date are the essential items, and a button to submit the request rounds everything off.

Drag a Label onto the form and set its Text property to “Name”. Position the label near the top-left corner; a convenient spot is coordinates (8, 40). Add a TextBox next to it, at (96, 40). Give the text box a meaningful name such as txtName so you can refer to it in code. Repeat this pattern for the age field: a label at (8, 64) with text “Age” and a TextBox at (96, 64) named txtAge

For the test date, drop a DateTimePicker onto the form. Place it at (96, 88) and rename it to dtpTestDate. Above this control, add a label that reads “Test Date” and position it at (8, 88). Finally, place a Button below the input fields, centered horizontally at (80, 128). Set the button’s Text property to “Create Appointment” and give it the name btnCreate. Add a title label at the top of the form - coordinates (16, 8) - and set its text to “Setup Driving Test Appointment” with a bold font to make the heading stand out.

At this point the form should look familiar: a small window with three rows of input, each paired with a label, and a submit button below. You can preview the layout by running the project in design mode. Make sure the controls line up nicely; a tidy arrangement helps users focus on the data entry without confusion.

Before moving forward, adjust the form’s properties to improve usability. Set the FormBorderStyle to SizableToolWindow so the form is slightly smaller than a standard dialog but still resizable. Change the StartPosition to CenterScreen so the window opens in the middle of the screen, drawing immediate attention. These tweaks are minor but they contribute to a smoother user experience.

With the visual elements in place, you’re ready to start adding validation logic that will enforce business rules and give instant feedback. The next step involves the ErrorProvider control, a built‑in component that displays error icons and tooltips next to controls that fail validation. Understanding how to integrate this control will allow you to deliver a polished, user‑friendly form that clearly communicates what needs to be corrected.

Connecting the ErrorProvider and Coding Validation Rules

The ErrorProvider component lives in the toolbox under “Components” and doesn’t show up in the form’s client area. Drag it onto the designer surface; it will appear in the component tray below the form. Name the component errProvider to keep the naming consistent with the rest of your controls.

Open the form’s code-behind file (Form1.cs) and locate the constructor that calls InitializeComponent(). After that call, add a line that assigns the form as the container control for the ErrorProvider:

Prompt
errProvider.ContainerControl = this;</p>

This line tells the ErrorProvider which form to associate itself with, enabling it to display error icons next to controls that belong to the form.

Now it’s time to wire up validation events. Every input control that requires validation exposes a Validating event. Double‑click the event in the Properties window to generate an event handler for txtName:

Prompt
private void txtName_Validating(object sender, CancelEventArgs e)</p> <p>{</p> <p> ValidateName();</p> <p>}</p>

Repeat the same process for txtAge and dtpTestDate, generating txtAge_Validating and dtpTestDate_Validating event handlers. Each handler simply calls a dedicated validation method; this keeps the event logic clean and lets you reuse the same validation code if needed.

Implement the ValidateName method. The rule is straightforward: the name field must not be empty. If it is empty, set an error on the txtName control and return false; otherwise clear any existing error and return true:

Prompt
private bool ValidateName()</p> <p>{</p> <p> if (string.IsNullOrWhiteSpace(txtName.Text))</p> <p> {</p> <p> errProvider.SetError(txtName, "Please enter your name");</p> <p> return false;</p> <p> }</p> <p> errProvider.SetError(txtName, string.Empty);</p> <p> return true;</p> <p>}</p>

Next, tackle the age field. The criteria are: the field cannot be blank, it must contain a numeric value, and the user must be at least 18 years old. The code below captures these checks. Notice how the int.TryParse method safely attempts to convert the text to an integer; if it fails, an error message appears:

Prompt
private bool ValidateAge()</p> <p>{</p> <p> if (string.IsNullOrWhiteSpace(txtAge.Text))</p> <p> {</p> <p> errProvider.SetError(txtAge, "Please enter your age");</p> <p> }</p> <p> if (!int.TryParse(txtAge.Text, out int age))</p> <p> {</p> <p> errProvider.SetError(txtAge, "Age must be a number");</p> <p> }</p> <p> if (age < 18)</p> <p> {</p> <p> errProvider.SetError(txtAge, "You must be at least 18 years old");</p> <p> }</p> <p> errProvider.SetError(txtAge, string.Empty);</p> <p> return true;</p> <p>}</p>

The date picker validation is a bit more business‑specific. The rule here is that test appointments can only be scheduled on weekdays. To enforce this, examine the dtpTestDate.Value.DayOfWeek property. If the selected date falls on a Saturday or Sunday, display an error. Otherwise, clear any existing error:

Prompt
private bool ValidateTestDate()</p> <p>{</p> <p> DayOfWeek day = dtpTestDate.Value.DayOfWeek;</p> <p> if (day == DayOfWeek.Saturday || day == DayOfWeek.Sunday)</p> <p> {</p> <p> errProvider.SetError(dtpTestDate, "Appointments may only be set on weekdays");</p> <p> }</p> <p> errProvider.SetError(dtpTestDate, string.Empty);</p> <p> return true;</p> <p>}</p>

Having defined these three validation methods, you can now validate the entire form when the user clicks the btnCreate button. Wire the button’s Click event to call a ValidateForm method:

Prompt
private void btnCreate_Click(object sender, EventArgs e)</p> <p>{</p> <p> ValidateForm();</p> <p>}</p>

Inside ValidateForm, invoke each individual validator. If all return true, display a success message; if any return false, alert the user to fix the errors. The MessageBox.Show calls make the outcome obvious:

Prompt
private void ValidateForm()</p> <p>{</p> <p> bool isNameValid = ValidateName();</p> <p> bool isAgeValid = ValidateAge();</p> <p> bool isDateValid = ValidateTestDate();</p> <p> if (isNameValid && isAgeValid && isDateValid)</p> <p> {</p> <p> MessageBox.Show("Appointment will be created now");</p> <p> }</p> <p> else</p> <p> {</p> <p> MessageBox.Show("Please correct the highlighted errors");</p> <p> }</p> <p>}</p>

Notice how the error icons appear as the user moves between controls or attempts to submit. Each icon displays a tooltip that describes the issue, making it clear what needs attention. The error provider’s default blink style and rate provide visual emphasis, but you can adjust those properties if you prefer a subtler or more pronounced effect. For instance, setting errProvider.BlinkStyle to NeverBlink eliminates the flashing and may be preferable for accessibility.

In addition to simple error icons, the ErrorProvider can show dataset column errors if you bind controls to data sources. While that feature isn’t required for this basic form, it demonstrates the versatility of the component. To use it, set the DataSource, DataMember, and ContainerControl properties, then call SetColumnError on the appropriate column. However, for the purpose of this example, the per‑control validation approach is sufficient.

Running the Form and Observing Validation in Action

Compile the project by pressing F5 or selecting Start Debugging from the Debug menu. The form should launch at the center of your screen. Try clicking the Create Appointment button without entering any data. You’ll immediately see three blinking icons beside the Name, Age, and Test Date controls. Hover over each icon, and a tooltip will display the corresponding error message. This instant visual feedback prevents the user from proceeding until all fields satisfy the validation rules.

Now fill in the Name field with “John Doe” and leave the Age field blank. Click the button again; the Age icon reappears while the Name icon disappears. This demonstrates that the ErrorProvider updates dynamically as individual validators run. Next, type “17” into the Age field. The Age icon shows an error about being under 18. Change the value to “20” and observe that the icon clears. The form responds immediately to each change because the Validating event fires whenever focus leaves a control.

When it comes to the date picker, test both a weekend and a weekday. If you pick a Saturday, the icon reappears with a tooltip that explains that appointments can only be set on weekdays. Choose a Monday and confirm that the icon is gone. The ErrorProvider’s default behavior is to show the icon only when an error exists; once the control passes validation, the icon automatically disappears.

Once all fields are valid - Name filled, Age at least 18, and a weekday date - the Create Appointment button will produce a message box saying “Appointment will be created now”. This confirms that the form’s overall validation logic works as intended. If you close the application and open it again, the form starts fresh with no errors displayed; the ErrorProvider only reacts to user input.

At this point you have a fully functional, validation‑aware Windows Form that uses the ErrorProvider component to guide users. You can extend the form by adding more fields or business rules, adjusting the error provider’s blink style, or even replacing the default error icon with a custom image. The essential pattern - attach the Validating event, perform checks, call SetError, and trigger a final form validation - remains the same across more complex scenarios.

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Related Articles