Manage Learn to apply best practices and optimize your operations.

Displaying errors with the error provider

Some code for improving error handling in .NET.

One of the more difficult parts of any user interface is error detection and notification. When the user fills out a form and submits it, the program must verify that the data is valid before saving it to a database or continuing with processing. If the program finds errors in the user's input data, then it must display some kind of error notification. Over the years, programmers have used many different error notification schemes with message boxes or form icons. Windows Forms formalizes and standardizes the error notification process with the ErrorProvider component. This article from InformIT provides some examples of the use of this component.


A Simple Example

As an example of using the ErrorProvider, consider a "New Contact" dialog box for a simple telephone book application.

Data entry rules are very simple. The user must enter values for both fields, and the Phone field must contain a 10-digit number entered with no punctuation. For example, the number (702)555-1212 would be entered 7025551212. If all of these conditions are met, the program accepts the data input, signified by a message box. If any one or more of the conditions is not met, the program should indicate the error and allow the user to fix it. The program indicates the error by placing an exclamation icon next to the control that is in error. The user can hover the mouse over the icon to see the error message.

There are several ways that you can do data validation. Some people like to let the user fill out the form completely and submit the data before any validation is performed. The program then validates each field and provides error messages for each invalid field. Others like to validate data on a per-field basis as the user is entering data. Very often you'll see forms take a hybrid approach wherein field validation ensures that the user's input is of the correct type (to check for blank fields, for example), and then post-submit validation makes sure that the form as a whole is valid, taking into account any fields that interact with each other.

The two visible controls on the form are named txtName and txtPhone. In addition, there is a non-visible control—an ErrorProvider instance—called erp1.

Field validation is accomplished by handling the control's Validating event, which is raised when the user moves away from a control. Within the event handler, the field's data is validated. If the data is not valid, the Cancel flag in the passed CancelEventArgs instance and an error message is set in the ErrorProvider. Here is the code for the two event handlers.

If you compile and run this code, you'll see that the program does indeed have the behavior described. But it's too restrictive. You can't close the program if there's an error on the field that you're entering. Setting e.Cancel in the Validating event handler prevents you from interacting with the rest of the form until the field you're editing is valid. This, as they say, is a problem.

Fortunately, the problem isn't very difficult to solve. First, just have the Validating event handlers do the validation, but don't have them set e.Cancel when validation fails. Second, you'll need to add a Click event handler for the Save button. This event handler will validate the form and display the success message box if all data fields pass muster. Here's the modified code:

[C#]
private void btnSave_Click(object sender, System.EventArgs e)
{
  if (IsNameValid() && IsPhoneValid())
  {
    MessageBox.Show(string.Format("Added {0}, {1}", txtName.Text, txtPhone.Text));
    txtName.Text = "";
    txtPhone.Text = "";
    txtName.Focus();
  }
}

private void txtName_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
  // validate name but don't cancel
  IsNameValid();
}

private void txtPhone_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
  // validate phone but don't cancel
  IsPhoneValid();
}
[Visual Basic]
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
  If (IsNameValid() And IsPhoneValid()) Then
    MessageBox.Show(String.Format("Added {0}, {1}", txtName.Text, txtPhone.Text))
    txtName.Text = ""

    txtPhone.Text = ""
    txtName.Focus()
  End If
End Sub

Private Sub txtName_Validating(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles txtName.Validating
  ' Validate but don't cancel
  IsNameValid()
End Sub

Private Sub txtPhone_Validating(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles txtPhone.Validating
  ' Validate but don't cancel
  IsPhoneValid()
End Sub

With that modified code, the program will correctly notify the user of input errors, and also will allow the user to close the program without having to validate. It is in the Save button's Click event handler that you'd want to add code to check for interactions between components.


Click over to InformIT to read more about the ErrorHandler Component.


Dig Deeper on Topics Archive

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchSoftwareQuality

SearchAWS

SearchCloudComputing

TheServerSide.com

Close