Home > SOA Tips > .NET Developer > Displaying errors with the error provider
SOA Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

.NET DEVELOPER

Displaying errors with the error provider


Jim Mischel
09.07.2004
Rating: -3.67- (out of 5)


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


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.


Rate this Tip
To rate tips, you must be a member of SearchSOA.com.
Register now to start rating these tips. Log in if you are already a member.




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


RELATED CONTENT
Platforms and Servers
Tracking down managed memory leaks
Handling exceptions in .NET
.NET Compact Framework graphics
The Data Access Application Block
Decision time: .NET or J2EE?
A great .NET resource: .Net2TheMax
Delegates vs. interfaces in .NET
Project structure best practices
Working with PDFs in a .NET environment
VS.NET 2005 betas

.NET Developer
Programming Indigo
DataSets and Web services don't mix
Security in .NET 2.0
Tracking down managed memory leaks
Handling exceptions in .NET
.NET Compact Framework graphics
The Data Access Application Block
A great .NET resource: .Net2TheMax
Delegates vs. interfaces in .NET
Project structure best practices

Microsoft .NET Web services
New SOA tools for Microsoft server
Yahoo proxy fight looms
New Microsoft site for architects
LAMP coders go hybrid route
Silverlight shines on bank RIAs
Microsoft fights on for Yahoo
New Microsoft language for SOA?
Ballmer details software-plus-services
Microsoft/Yahoo could rock Web services world
SOA needs information management
Microsoft .NET Web services Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
Common Language Infrastructure  (SearchSOA.com)
Visual J#  (SearchSOA.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.

About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides enterprise IT professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective IT purchase decisions and managing their organizations' IT projects - with its network of technology-specific Web sites, events and magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Reprints  |  Site Map




All Rights Reserved, Copyright 2001 - 2008, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts