Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft C# Professional Projects - Premier Press.pdf
Скачиваний:
177
Добавлен:
24.05.2014
Размер:
14.65 Mб
Скачать

176 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

Validation and exception handling form an integral part of any business application. Your application needs to be robust to withstand any anomalies of

application execution.

Anomalies in an application can occur because of unexpected conditions. For example, you may design your application to open a file in the write mode. Although the code will not generate any error if the file is closed, if a user opens the file in another application and then executes your application, your application can generate an unrecoverable error. To avoid such run-time errors, you should implement an exception-handling mechanism in your application.

Exception handling provides many uses in an application. For example, if a user specifies the date in an incorrect format, the user can be allowed to rectify the error and proceed with the registration. Similarly, if the databases pertaining to the application are not responding, the application can display a message to that effect and allow the user to select an alternate location for the database.

This chapter provides an in-depth coverage of the exception-handling capabilities of Visual C#. You will apply exception-handling logic to the Customer Maintenance project. In addition, Visual Studio .NET provides a number of debugging tools that you can use to debug your application.This chapter will also introduce you to the debugging tools and help you use the important ones to debug your application.

Performing Validations

You should always validate data in a Windows form before updating the data in a database. This method has several benefits, some of which include:

Improved response time. The response time of an application is shorter because the application does not need to attempt to update the data in the database and then retrieve an error message because of incorrect data.

Accuracy of data. The application is less prone to sending incorrect data to the database.

VALIDATIONS AND EXCEPTION HANDLING

Chapter 9

 

177

 

 

 

 

 

Improved database performance. The load on the database is reduced because it processes optimal transactions only.

In this section, you can learn to validate data for the JobDetails form of the Customer Maintenance project.

Identifying the Validation Mechanism

There are several mechanisms to ensure that only valid values are specified in a user form. Some of these ways are given in the following list:

Selecting the appropriate Windows control for accepting data

Trapping incomplete data when users navigate from one control to another

Validating the form before submitting records to the database

I will now explain each method described here one by one.

Selecting Windows Controls

Often, you can eliminate common errors by using the correct type of controls. For example, instead of using a text box for accepting date values from users, you can use the DateTimePicker control. Similarly, you can use the ListBox control to make the user select an option from a range of options or use the RadioButton control to accept one value from a range of values. In this way, the choices available to the user are limited and the user is less likely to make a mistake.

In the JobDetails form, the value for the JobDate field should be in the date format. Therefore, instead of using a TextBox control, you should use the DateTimePicker control. The steps to add the DateTimePicker control to the form are given in the following list:

1.Open the Customer Maintenance project.

2.Double-click on the JobDetails.cs form to open the code-behind file.

3.Delete the TextBox control from the JobDate field.

4.Drag a DateTimePicker control from the Toolbox to the form.

The changed form, which is obtained after completing the preceding steps, is shown in Figure 9-1.

178 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

FIGURE 9-1 Adding a DateTimePicker control to the for m

 

Y

L

F

M

 

A

 

E

 

Run the applicationTand open the JobDetails form. You will notice that the current date automatically appears in the form. Similarly, when data is loaded from the database, the JobDate field changes to the one that was specified while adding the record, as shown in Figure 9-2.

FIGURE 9-2 Displaying date and time data from a database

Team-Fly®

VALIDATIONS AND EXCEPTION HANDLING

Chapter 9

 

179

 

 

 

 

 

Trapping Incomplete Data

There are certain fields in a database that cannot be left blank when you add records to the database. For example, the CMS (Customer Maintenance System) database uses the tblJobDetails table to store records pertaining to the JobDetails form. Follow these steps to check the fields that are mandatory in the

tblJobDetails table:

1.Open SQL Ser ver Enterprise Manager.

2.In the SQL Server Enterprise Manager window, click on the + (plus) sign next to the name of the SQL server on which the database is installed.

3.In the SQL Server node, expand the CMS database, which stores the

tblJobDetails table.

4.Click on Tables. The tables in the CMS database will appear.

5.Right-click on tblJobDetails and select Properties. The Table Properties - tblJobDetails dialog box will appear. This dialog box shows the fields of the table in which you can have null values, as displayed in Figure 9-3.

FIGURE 9-3 Mandatory fields in a table

180 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

As you can see in Figure 9-3, the CarNo, JobDate, and WorkerId fields are mandatory in the database.The CarNo, JobDate, and WorkerId controls on the JobDetails form represent these fields.

To ensure that a user has specified values for the three fields described above, there are two methods. Either you can validate the required field as soon as a user moves out of it, or you can validate the entire form when the user clicks on the Add or Update button. I examine the procedure to validate an entire form in the next section. In this section, I will describe the ways to validate one field at a time.

When a user selects a control, the Enter event of the control is generated. Similarly, when a user deselects a control, the Leave event of the control is generated. You can use these events to validate controls.

Begin by ensuring that the user has specified a valid car number before the user proceeds to specify the date. When a user tabs out of the CarNo control, the Enter event of the JobDate control and the Leave event of the CarNo control are generated.Therefore, you can check whether the user has specified a valid value for the CarNo either in the Enter event of the JobDate control or in the Leave event of the CarNo control. If the user has not specified a valid value, you can reactivate the CarNo control. To code the functionality, follow these steps:

1.Click on the editCarNo text box in the design view of the JobDetails form.

2.In the Properties window, click on the Events button (the button that has the yellow lightning symbol). All the events available for the TextBox control will appear.

3.From the list of available events, double-click on Leave. The location of this option in the Properties window is shown in Figure 9-4.

4.When you double-click on Leave, Code Editor opens and the event handler for the Leave event is defined. Write the following code for the

Leave event of the editCarNo text box:

private void editCarNo_Leave(object sender, System.EventArgs e)

{

if ((editCarNo.Text==””) || (editCarNo.Text==null))

{

MessageBox.Show(“Please specify a valid value for the car number”,”Error in input”);

VALIDATIONS AND EXCEPTION HANDLING

Chapter 9

181

 

 

 

FIGURE 9-4 Adding event handlers for controls

editCarNo.Focus();

}

}

After writing the preceding code, compile and run the application. If you attempt to specify a blank value in the editCarNo text box, the application will display an error message and bring the text box into focus, as shown in Figure 9-5.

FIGURE 9-5 Validating data in controls

182 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

The preceding method has two main drawbacks:

The user cannot decide the order in which controls should be filled. For example, if the user wishes to fill WorkerId before CarNo, the user cannot do so.

The control generates an error message when a user closes the form without specifying a valid value in the CarNo field. This is because the

Leave event of the control is fired even when the user closes the form. Therefore, even if the user decides to discard all changes and close the form, the error message is generated.

To overcome these drawbacks, you can validate data in all the controls when the user clicks on the Update or Add button. This method will be discussed in the next section.

Validating a Form

You can validate data in the JobDetails form in the Click event of the Update button. Validating all the controls simultaneously saves you the effort of coding events for each TextBox control separately. To validate the JobDetails form:

1.Open the JobDetails form in the Design view.

2.Double-click on the Update button. Code Editor opens.

3.Write the following code for the Click event of the JobDetails form:

if (editCarNo.Text.Length <6)

{

MessageBox.Show(“Please specify a valid car Number”); editCarNo.Focus();

return;

}

if (Convert.ToInt32(editWorkerId.Text)<1)

{

MessageBox.Show(“Please specify a valid worker ID”); editWorkerId.Focus();

return;

}