Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Premier Press - C# Professional Projects

.pdf
Скачиваний:
475
Добавлен:
12.02.2016
Размер:
14.7 Mб
Скачать

198 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

In most real-life projects, your application needs to interact with a database. To do so, Visual Studio .NET provides you with the ADO.NET data access model

that helps your application to communicate with data sources, such as a Microsoft

SQL Server and Oracle.

Y

 

L ADO.NET enables you to modify, Fadd, or delete data from the data source. To

ADO.NET is mainly designed to provide data access for distributed applications,

such as Web applications. In addition to accessing data from a data source,

provide data access, ADO.NET contains data providers, such as Microsoft Jet OLE DB Provider, Microsoft OLE DB Provider for Oracle, Microsoft OLE DB

E In this chapter, youTwill learn to connect the Windows forms that you have cre-

Provider for SQL Server, and so on. These data providers are used to connect to

a corresponding data source, enabling users to access and modify the data in the

data source.

M

A

 

ated for the Customer Maintenance project to the corresponding data source. In addition, you will add functionality to the data-bound controls used in these Windows forms. Finally, you will learn to create a form by using the Data Form Wizard.

Connecting Windows Forms

to a Data Source Using ADO.NET

You have seen the design of the database in Chapter 7, “Project Case Study.” In addition, you have created forms for the Customer Maintenance project in Chapter 8, “Windows Forms and Controls.” You will now learn to connect the forms that you have created to the Customer Maintenance database.

Creating Form1

Before connecting the WorkerForm, CustomerForm, and JobDetails form to the corresponding data sources, you can add functionality to the menu items that you created in Form1.

Team-Fly®

DATABASE INTERACTION USING ADO.NET

Chapter 10

199

 

 

 

 

Form1 contains menu items used to display the corresponding forms. You have already created these menu items; however, they are not functional. You can add the code to these menu items to make them functional. To do so, perform the following steps:

1.Double-click on menuItem1 to display the code window.

When the user clicks the Worker menu item, WorkerForm should be displayed. In addition, Form1 should be hidden.

2.To display WorkerForm, add the following code to the Click event of

menuItem1.

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

{

WorkerForm newForm = new WorkerForm(); newForm.ShowDialog(this);

}

The previous code creates an instance of WorkerForm named newForm and then calls the ShowDialog() method to display WorkerForm.The ShowDialog() method is used to display WorkerForm as a modal dialog box. As you can see, the ShowDialog() method has a parameter this. Using the keyword this enables you to declare Form1 as the parent form of WorkerForm.

Similarly, you can write the code for the Customer menu item, the Job Details menu item, and the Reports menu item, which are used to display the CustomerForm, the JobDetails form, and the Reports form, respectively.

The Exit menu in Form1 is used to close Form1. Therefore, you need to call the Close() method of the Form class as follows:

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

{

this.Close();

}

MODAL AND MODELESS FORMS

Visual Studio .NET allows you to display a form or a dialog box as modal or modeless in a MDI (multiple-document interface) application. A modal dialog box, when active, does not allow you to work with any other form in the application. Therefore, you need to close the form to work with another form in the application. You may even hide the modal form to work with another form.

However, a modeless dialog box allows you to work with another form in the application even if you do not close the modeless form.

200 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

Connecting WorkerForm to the Workers Table

In Chapter 8, you created a WorkerForm with a DataGrid control and four Button controls. However, these controls are not functional. You can now add code for these controls to make them functional.

Adding Functionality to the DataGrid Control

Before adding code to make a DataGrid control functional, you first need to understand what a DataGrid control is.

A DataGrid control is a type of a data-bound control that is used to display the data from a data source.The data from the data source is displayed in the form of a grid containing rows and columns. You can use a DataGrid control to add, delete, or modify records from an associated data source. In addition, you can use a DataGrid control to display data from one or more tables.

To display the data in a DataGrid control, you first need to bind the control to a data source by using ADO.NET. When a DataGrid control is bound to a data source, Visual Studio .NET automatically creates the rows and columns to display the data. In addition, the data from the data source is loaded to a DataSet object that you create.

A DataSet object is a memory cache that provides a relational view of the data from the data source. You can create a dataset to hold data from one or more tables. In addition to displaying the data from a data source, a dataset can be used to store relationships between the tables and the constraints defined for the table.

You will now create a DataSet object that contains data from the tblWorker table, which you need to display in the DataGrid control. To create a dataset, you first need to connect to the SQL server that contains the Customer Maintenance database. To do this, Visual Studio .NET provides you with several data adapters,such as OleDbDataAdapter and SqlDataAdapter. These data adapters act as an interface between the dataset and the underlying data source. This implies that a dataset uses a data adapter to communicate with the underlying data source. A data adapter is used to perform the functions of reading and writing data from a dataset to a data source and vice versa.

To create a data adapter, perform the following steps.

1.Drag SqlDataAdapter from the Data toolbox.

The Data Adapter Configuration Wizard is displayed.

DATABASE INTERACTION USING ADO.NET

Chapter 10

201

 

 

 

 

TIP

If you need to connect to a database other than a SQL database, you need to use the OleDbDataAdapter.

2.Click on the Next button to start the wizard.

3.In the Choose Your Data Connection page, click on the New Connection button to create a new connection to a SQL database.

The Data Link Properties window is displayed.

4.In the Provider tab of the Data Link Properties window, select the OLE DB provider to which you want to connect.

The Microsoft OLE DB Provider for SQL Server option is selected by default. In this case, you will use this option because you need to connect to a SQL database. To connect to some other database, you can select the appropriate option from the OLE DB Provider(s) list.

5.Click on the Next button to proceed with the wizard.

The Connection page of the Data Link Properties window is displayed.

6.From the Select or enter a server name: combo box, select the server to which you want to connect.

TIP

You can also type the name of the server in the combo box.

7.In the Enter information to log on to the server: group box, select the authentication mode to connect to a SQL server.

The Enter information to log on to the server: group box provides you with two radio buttons. To connect to a SQL server by using the Windows authentication mode, you select the Use Windows NT Integrated Security radio button.

202 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

However, if you select the Use a specific name and password: radio button, you need to specify the user name and the password in the User name: and Password: text box, respectively. To leave the password blank, check the Blank password check box.

8.Select the Select the database on the server: radio button to select a name of the database to which you want to connect.

9.Select the name of the database from the drop-down list.

Here, the name of the database is CMS. You may also type the name of the database in the combo box.

10.Click on the Test Connection button to test the connection to the CMS database.

A message box showing the text Test connection succeeded. is displayed if the connection is successful.

11.Click on the OK button to close the message box.

12.Click on the OK button to close the Data Link Properties window.

The Choose Your Data Connection page is displayed.The name of the database is displayed in the Which data connection should the data adapter use? list box.

13.Click on the Next button to proceed with the wizard.

The Choose a Query Type page is displayed. The page provides you with several options that the data adapter can use to access the database.

14.Select the Use SQL statements radio button.

This option allows you to create a SQL statement that enables the data adapter to access the database.

15.Click on the Next button.

The Generate the SQL statements page is displayed. You can type the query in the What data should the data adapter load into the dataset? text box.

16.Type the following SQL statement in the text box:

SELECT WorkerId, Name

FROM tblWorker

DATABASE INTERACTION USING ADO.NET

Chapter 10

 

203

 

 

 

 

 

 

This SQL statement allows you to select the WorkerId field and the Name field from the tblWorker table. You can also click on the Query Builder button to graphically create the query. The Data Adapter Configuration Wizard uses this SQL statement to create the Insert, Update, and Delete statements to insert, modify, and delete records from the

tblWorker table.

17.Click on the Next button.

The View Wizard Results page is displayed. This page displays a list of tasks that the wizard has performed.The Data Adapter Configuration Wizard creates Select, Insert, Update, and Delete statements. In addition, the wizard creates table mappings for your database.

18.Click on the Finish button to create the data adapter.

The Data Adapter Configuration Wizard creates a data adapter with the name sqlDataAdapter1, which contains information about the table and the fields to which the connection is made. In addition, the Data Adapter Configuration Wizard creates a connection named sqlConnection1 that contains the information about accessing the CMS database.

After creating a connection by using the Data Adapter Configuration Wizard, you need to generate a dataset. Visual Studio .NET automatically creates a DataSet object when you select the Generate Dataset option in the Data menu. To generate a dataset, perform the following steps:

1.Click anywhere in the form to activate it.

2.In the Data menu, select the Generate Dataset option. The Generate Dataset window is displayed.

3.From the Choose a dataset: group box, select the New radio button. In the text box adjacent to the New radio button, type the name of the DataSet object as workerDataSet.

Make sure that the tblWorker table is selected in the Choose which table(s) to add to the dataset text box.

4.Check the Add this dataset to the designer. check box.

204 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

Selecting the Add this dataset to the designer. check box ensures that the DataSet object is added to the component tray at the bottom of the form in the design view.

5. Click on the OK button to close the Generate Dataset window.

A DataSet object with the name workerDataSet1 is created. In addition, Visual Studio .NET creates a schema file named workerDataSet1.xsd in the Solution Explorer window. This file contains the definition of the dataset. You can doubleclick on the workerDataSet1.xsd file to view the definition of the dataset.

The dataset that you have created contains the data from the tblWorker table. However, the data is still not visible to the user. To display the records from the table, you need to bind the DataGrid control to the workerDataSet1 dataset. Performing the following steps will bind the DataGrid control to the dataset.

1.In the Design view, click on the DataGrid control to display its properties.

If the Properties window is not displayed, select the Properties Window option from the View menu or press the F4 key.

2.In the Properties window, select the DataSource property.

3.Click on the Down Arrow button to display the list of DataSet objects.

4.From the list that is displayed, select the workerDataSet1 option.

5.Click on the Down Arrow button of the DataMember property. A list of tables in the data source is displayed.

6.Select tblWorker from the displayed list.

A DataGrid control showing the column headings is displayed.

7.Save the form by clicking on the Save option in the File menu.

Figure 10-1 shows the WorkerForm with the DataGrid control.

DATABASE INTERACTION USING ADO.NET

Chapter 10

 

205

 

 

 

 

 

 

FIGURE 10-1 The WorkerForm with the DataGrid control

As you can see, the DataGrid control contains only the column headings. Visual Studio .NET does not automatically load the records from the table to the DataGrid control. To do so, you need to write the code for the Edit button.

Adding Functionality to the Edit Button

While creating the WorkerForm, you have included four Button controls to the form. However, until now, you have not added code to the buttons. In this section, you will write the code for the Click event of the Edit button that loads the records from the data source to the DataGrid control. To do so, perform the following steps:

1.Double-click on the Edit button to open the code window.

2.Add the following code to the Click event of the button.

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

{

workerDataSet1.Clear(); sqlDataAdapter1.Fill(workerDataSet1);

}

The previous code calls the Clear() method of the System.Data.DataSet class, which is used to clear records from the tables in the workerDataSet1 dataset.Then, the Fill() method of the data adapter is called to load the records in the dataset. The Fill() method accepts the name of the DataSet object as the parameter.

206 Project 1 CREATING A CUSTOMER MAINTENANCE PROJECT

TIP

If you are using an OleDbDataAdapter to connect to a database, include the following code in the Click event of the Edit button.

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

{

workerDataSet1.Clear(); oleDbDataAdapter1.Fill(workerDataSet1);

}

When the user clicks on the Edit button,the records from the tblWorker table get loaded in the DataGrid control. You can resize the control to display as many records as you want. However, if the records are more than the space provided, a scroll bar is introduced in the DataGrid control. Figure 10-2 shows WorkerForm with the records displayed from the tblWorker table.

FIGURE 10-2 WorkerForm with the records displayed

Adding Functionality to the Save Button

The Edit button allows you only to view the records.However, when you perform any modifications to the records that are displayed, the updated record is saved only in the dataset.To replicate the changes made by the user to the records in the data source, you need to write the code for the Save button.

DATABASE INTERACTION USING ADO.NET

Chapter 10

207

 

 

 

 

Visual Studio .NET provides you with an Update() method of the data adapter that you can use to make changes in the underlying data source. Writing the following code in the Click event of the Save button will call the Update() method.

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

{

sqlDataAdapter1.Update(workerDataSet1); MessageBox.Show(“The Worker table is updated.”);

}

You can make the following changes to the previous code if you are using OleDbDataAdapter.

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

{

oleDbDataAdapter1.Update(workerDataSet1); MessageBox.Show(“The Worker table is updated.”);

}

The Update() method includes the statements for adding, deleting, and modifying records in the database. When a user makes changes to the records and clicks the Save button, the Update() method is called. The Update() method checks the value of the RowState property to identify the index of the row to which the user has made changes. The Update() method then executes the Insert, Delete, or Update command as required.

When the changes are updated to the tblWorker table, a message box displaying the text The Worker table is updated. is shown. Figure 10-3 shows the message box displaying the message that the changes are updated to the database.

FIGURE 10-3 WorkerForm with the message box displayed