An ExampleCustomer Maintenance


An Example—Customer Maintenance

As an example, consider a simple scenario. You have been asked to build a Customer Maintenance application. Part of the application needs to record the essential details of a customer, including title, name, and gender. You decide to create a form like the one shown in the following graphic.

graphic

You need to ensure that the user's input is consistent; the title (Mr, Mrs, Miss, or Ms) must match the selected gender (Male or Female), and vice versa.

A First Attempt at Performing Validation

In the following exercises, you will examine the Customer Maintenance application and run it to see how easily you can get validation wrong.

Examine the program

  1. Open the CustomerDetails project, located in the \Microsoft Press\Visual CSharp Step By Step\ Chapter 22\CustomerDetails folder in your My Documents folder.

  2. In the Solution Explorer, double-click CustomerForm.cs to display the Customer Details form in Design View.

  3. Click the Title combo box on the form, and then click the Items property in the Properties window. It should appear as (Collection). Click the Ellipses button to display the strings in the collection.

    graphic

    You can see from this collection that the list box contains four titles: Mr, Mrs, Miss, and Ms. Click Cancel to close the String Collection Editor window.

  4. Examine the Gender group box and radio buttons. The group box contains two radio buttons called Male and Female.

    The application enforces the business rule that the gender and the title must match. If the title is Mr, the gender must be male, and if the title is Mrs, Miss, or Ms, the gender must be female.

  5. On the View menu, click Code to switch to the Code And Text Editor window displaying CustomerForm.cs. Look at the checkTitleAndGender method situated immediately below the CustomerForm constructor:

    // Cross check the gender and the title to make sure they correspond private bool checkTitleAndGender() {     if (title.Text == "Mr")     {         // Check that gender is Male         if (!male.Checked)         {              MessageBox.Show("If the title is Mr the gender must be male", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);             return false;         }     }     else     {         // Check that the gender is Female         if (!female.Checked)         {             MessageBox.Show("If the title is Mrs, Miss, or Ms the gender must be female", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);             return false;         }     }     // Title and gender match     return true; }

    This method performs a simple cross-check between the contents of the Title combo box and the radio buttons in the Gender group box. If the title is “Mr,” the business rule states that the gender must be male, and the method checks to ensure that the Male radio button is selected. If this option is not selected, the method displays an error message and returns false. Likewise, if the title is one of the other values (Mrs, Miss, or Ms), the business rule states that the gender must be female, and the method looks at the Female radio button to ensure it is selected. Again, if this is not the case, a different error message is displayed and the method returns false. If the title and the gender match, the method returns true.

  6. Look at the titleValidating and genderValidating methods at the end of the file. These are implementations of the Validating event handler for the Title combo box and the Gender group box. They both call the checkTitleAndGender method, and then set the Cancel property of the CancelEventArgs parameter to true if the checkTitleAndGender method returns false:

    private void titleValidating(object sender, CancelEventArgs e) {     if (!checkTitleAndGender())    {         e.Cancel = true;     } } private void genderValidating(object sender, CancelEventArgs e) {     if (!checkTitleAndGender())     {         e.Cancel = true;     } }

  7. Examine the remaining methods, exitClick and saveClick. The form has a menu strip with a File menu, containing Save and Exit items. These two methods are called when the user clicks either of these two menu items. The exitClick method closes the form and exits the application. The saveClick method displays the message “Customer Saved” (this is just a prototype form—the production version would actually save the information somewhere).

Now you'll run the application and see what happens when it tries to validate the user's input.

Run the application

  1. On the Debug menu, click Start Without Debugging to run the application.

    The Customer Details form appears. Notice that the default gender is Male.

  2. Select Mrs from the Title combo box and tab to or click the first Name text box.

    Notice that the checkTitleAndGender method generates and displays an error message because the title and the gender don't agree.

  3. Click OK in the Error dialog box to close it, and then try to click the Female radio button in the group box.

    You will fail, as the CausesValidation property of the group box makes the Validating event run again, causing the error message to be displayed once more.

  4. Click OK in the Error dialog box. Set the title to Mr and click the Female radio button.

    Remember that the Validating event fires just before the focus is passed to the Female radio button. When the checkTitleAndGender method is called, the title (Mr) and the gender (male) will agree. You are successfully able to set the gender to female.

  5. Now that you have now set the gender to female, try to save the customer's details by clicking Save in the File menu. This action works without error and the message Customer Saved appears in a message box. Confused? Click OK.

  6. Correct the (non-reported) error by trying to set the title to Mrs.

    The Validating event (this time for the Gender group box) runs, spots that the gender and title don't match, and then displays an error. You will not be able to escape until you set the Gender to Male again (but then you are back to square one).

  7. Exit the application.

The validation strategy failed because the Validating event fires only when you move to another control on the same form (and not to a control in a toolbar or a menu bar, for example). Developers often put much effort into getting it all to work. The next sections explain how to get it to work by using the tools properly.

TIP
Use the Validating event to validate controls in isolation only; don't use it to check the contents of one control against another.

Being Unobtrusive

The issue with the Customer Maintenance application is that the validation is performed at the wrong time, is inconsistently applied, and interferes too much. The actual logic is fine though. We just need an alternative approach to handling the validation.

A better solution would be to check the user's input when the user saves the data. This way you can ensure that the user has finished entering all the data and that it is consistent. If there are any problems, an error message will appear and prevent the data from being saved until the data is corrected. In the following exercise, you will change the Customer Maintenance application to postpone validation until the customer information is saved.

Change the point where data is validated

  1. Return to the Design View window displaying CustomerForm. Click the Title combo box.

  2. In the Properties window, click the Events button. Scroll down to the Validating event, and then delete the titleValidating method.

    This unsubscribes the Title combo box from the Validating event.

  3. On the CustomerForm, select the Gender group box.

  4. In the Properties window, click the Events button. Find the Validating event, and then delete the genderValidating method.

    IMPORTANT
    Unsubscribing from an event in this way detaches the event method from the event itself but does not delete the event method—if you no longer need the method, you can remove it manually in the Code And Text Editor window.

  5. Display the file CustomerForm.cs in the Code And Text Editor window. Delete the title-Validating and genderValidating methods. You are going to call the checkTitleAndGender method when the Save menu item is clicked.

  6. Locate the saveClick method. This is where you are going to place the validation code. Modify this method as shown below:

    private void saveClick(object sender, EventArgs e) {     if (checkTitleAndGender())     {         // Save the current customer's details         MessageBox.Show("Customer saved", "Saved");     }     else     {         MessageBox.Show("Customer title and gender are inconsistent" +                         " – please correct and save again", "Error",                         MessageBoxButtons.OK, MessageBoxIcon.Error);     } }

    The if statement calls the checkTitleAndGender method. If the method returns true, the saveCustomerForm method displays the “Customer Saved” message box. If the checkTitleAndGender method returns false, an error message box is displayed and the customer's details are not saved.

Test the application again

  1. Build and run the application. When the Customer Details form appears, set the Title combo box to Mrs, and then click in the first Name text box. This should work without error because the Validating event is no longer trapped by the Title combo box.

  2. Verify that the Male radio button is selected, and then click the Save item in the File menu. At this point, the checkTitleAndGender method is called and the inconsistency is reported. Click OK.

  3. Notice that another message box occurs—this is the message reported by the saveClick method. Click OK again.

  4. Select the Female radio button, and then click the Save Customer button on the toolbar.

    This time no errors are reported and Customer Saved message box is displayed.

  5. Click OK, and exit the application.

Using an ErrorProvider Control

Postponing validation is good and makes the form less frustrating to use. But what happens if there are several validation errors reported when the data is saved? If you use message boxes to present error information, you might end up displaying several of them in succession if there are multiple errors. Additionally, the user will have to remember each error so that it can be corrected. This can get tedious for a user after more than two or three errors are reported. A much better technique is to use an ErrorProvider control as shown in the following exercise.

Add an ErrorProvider control

  1. Return to CustomerForm in the Design View window.

  2. In the Toolbox, expand the Components category. Click the ErrorProvider control and drop it anywhere on the form.

    It appears under the form.

    graphic

  3. Click the errorProvider1 control, and select the Properties window. Change the (Name) property to errorProvider and verify that the BlinkStyle property is set to BlinkIfDifferentError.

    When an error is reported by a control, an error icon (which you can select by setting the Icon property) appears by the control in error and blinks for a short while and then remains static. You can change the BlinkRate property if you want to make it blink faster or slower—the default rate is 250 milliseconds (four times a second). If a subsequent error is reported, the icon blinks only if the error is different from the current one. If you want the icon to blink every time, you can set its BlinkStyle to AlwaysBlink.

    On the CustomerForm, select the Title combo box. If you look at the Properties window, you will discover a new property called Error on errorProvider. This property only appears when an ErrorProvider control has been added to a form, and is titled accord- ing to the name of the ErrorProvider control. If you type a message here (such as “Testing”), an error icon appears next to the Title combo box. If you hold the mouse pointer over the error icon, a ToolTip appears displaying the error message.

    If you leave this property set as it is, the error icon is always displayed, which is not what you want. The icon should be displayed (with a meaningful error message) only in the event of an error, so delete the text “Testing” from the Error on errorProvider property. You will write some code to dynamically use the errorProvider control shortly.

  4. Switch to the Code And Text Editor window for CustomerForm. Locate the checkTitleAndGender method and replace the statements that call MessageBox.Show with invocations of the errorProvider.SetError method, as shown here:

    // Cross check the gender and the title to make sure they correspond private bool checkTitleAndGender() {     if (title.Text == "Mr")     {         // Check that gender is Male         if (!male.Checked)         {             errorProvider.SetError(gender, "If the title is Mr " +                 "the gender must be male");             errorProvider.SetError(title, "If the gender is " +                 "female the title must be Mrs, Miss, or Ms");             return false;         }     }     else     {         // Check that the gender is Female         if (!female.Checked)         {             errorProvider.SetError(gender, "If the title is Mrs, " +                 "Miss, or Ms the gender must be female");             errorProvider.SetError(title, "If the gender is male " +                 "the title must be Mr");             return false;         }     }     // Title and gender match - clear any errors     errorProvider.SetError(gender, "");     errorProvider.SetError(title, "");     return true; }

    The SetError method of the ErrorProvider control specifies which control to mark with an error icon and the message to be displayed as a ToolTip. If you provide an empty string as the second parameter, as the code does at the end of the method, the error icon is removed.

Test the ErrorProvider control

  1. Build and run the application.

  2. Select Mrs in the Title combo box, and then verify that the Male radio button is selected.

  3. On the File menu, click Save. A message box appears indicating that the save failed, and error icons are displayed next to the controls that are in error. Click OK. If you hover the mouse pointer over each of the error icons, you see the error message, as shown in the graphic on the next page.

    graphic

    This is a much less intrusive but more reliable and consistent type of validation than the original application contained.

  4. Select the Female gender radio button and click the Save item on the File menu.

    As the data is now consistent, you will see the Customer Saved message box and the error icons will disappear.

  5. Exit the application.

Adding a Status Bar

Although some of the message boxes have disappeared, some still remain—a message box appears when customer information is successfully saved or if an error occurs. This is feedback that the user needs to be able to see, but it is annoying to the user to have to click the OK button to acknowledge the messages. A better way to inform the user of these situations is to display the messages in a status bar at the bottom of the form; the user can still see them, but does not have to click anything to move them out of the way.

In the final exercise in this chapter, you will implement a status bar in the CustomerForm form by using a StatusStrip control.

Add a StatusStrip control

  1. Return to CustomerForm in the Design View window.

  2. In the Toolbar, expand the Menus & Toolbars category. Drag a StatusStrip control from the Toolbar onto the form.

    The control appears underneath the form, and a status bar is added to the base of the form.

    graphic

  3. Click the statusStrip1 control, and select the Properties window. Change the (Name) property to statusStrip.

  4. In the status bar on the form, click the drop-down arrow as shown in the following graphic, and click StatusLabel.

    graphic

    This action adds a ToolStripStatusLabel control to the status bar. This is a version of the Label control that is intended for use in tool strips and status bars.

  5. Click the toolStripStatusLabel1 control in the status bar. Using the Properties window, change its name to statusMessages. Clear the Text property.

    The control shrinks in size, but is still present in the status bar.

  6. Switch to the Code And Text Editor window for CustomerForm. Find the saveClick method. This method contains the MessageBox statements that you need to convert into status bar messages.

  7. Change the first MessageBox statement (in the if statement) to display a message in the status bar instead, as follows:

    statusMessages.ForeColor = Color.Black; statusMessages.Text = "Customer Saved";

    You will see why you need to set the text color to black in the next step.

  8. Change the second MessageBox statement (in the else statement) to display the following error message in the status bar:

    statusMessages.ForeColor = Color.Red; statusMessages.Text = "Customer title and gender are inconsistent. Changes not saved";

    The error message is displayed in red to make it stand out. When an ordinary information message (such as “Customer Saved”) is displayed, the color should be reset back to black.

Test the status bar

  1. Build and run the application. (A finished version is available in the \Microsoft Press\Visual CSharp Step By Step\Chapter 22\CustomerDetails Complete folder in your My Documents folder, if you need it.)

  2. Select Mrs in the Title combo box, and then verify that the Male radio button is selected.

  3. On the File menu, click Save.

    A red error message appears in the status bar indicating that the save failed. The error icons are displayed next to the controls that are in error, as before.

  4. Select the Female gender radio button and click the Save item on the File menu.

    You will see the Customer Saved message in the status bar (in black) and the error icons will disappear.

  5. Exit the application.

  • If you want to continue to the next chapter

    Keep Microsoft Visual Studio 2005 running and turn to Chapter 23.

  • If you want to exit Visual Studio 2005 for now

    On the File menu, click Exit. If you see a Save dialog box, click Yes.




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net