64
Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Embed Size (px)

Citation preview

Page 1: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Connecting

to

Data Sources

Using

ADO.NET

Dr. Awad Khalil

Computer Science & Engineering Department

AUC

Page 2: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

2

ADO.NET Object Model An application connects to and interacts with a relational

database via a database interface – software that facilitates communication between a Database Management System (DBMS) and a program.

C# programs communicate with databases and manipulate their data through ADO.NET .

The ADO.NET object model provides an API for accessing database systems programmatically.

ADO.NET was created for the .NET framework to replace Microsoft’s ActiveX Data Objects (ADO) technology.

The IDE features visual programming tools that simplify the process of using a database in applications.

Page 3: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

3

Namespaces System.Data, System.Data.OleDb and System.Data.SqlClient

Namespace SystemData is the root namespace for the ADO.NET API.

The other important ADO.NET namespaces, System.Data.OleDB and System.Data.SqlClient, contain classes that enable programs to connect with and manipulate data sources – locations that contain data, such as a database or an XML file.

Namespace System.Data.OleDB contains classes that are designed to work with any data source, where as System.Data.SqlClient contains classes that are optimized to work with Microsoft SQL Server databases.

Page 4: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

4

Class SqlConnection

An object of class SqlConnection (nanespace System.Data.SqlClient) represents a connection to a database source – specifically a SQL Server database.

A SqlConnection object keeps track of the location of the data source and any settings that specify how the data source is to be accessed.

A connection is either active (i.e., open and permitting data to be sent to and retrieved from the data source) or closed.

Page 5: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

5

Class SqlCommand

An object of class SqlCommand (namespace System.Data.SqlClient) represents SQL command that a DBMS can execute on a database.

A program can use SqlCommand objects to manipulate a data source through a SqlConnection.

The program must open the connection to the data source before executing one or more SqlCommands and close the connection once no further access to the data source is required.

A connection that remains active for some length of time to permit multiple data operations is known as a persistent connection.

Page 6: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

6

Class DataTable

Class DataTabel (namespace System.Data) represents a table of data. A DataTable contains a collection of DataRows that represent the table’s data.

A DataTable also has a collection of DataColumns that describe the columns in a table.

DataRow and DataColumn are both located in namespace System.Data.

An object of class System.Data.DataSet, which consists of a set of DataTables and the relationships among them, represents a cache of data – data that a program stores temporarily in local memory.

The structure of a DataSet mimics the structure of a relational database.

Page 7: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

7

ADO.NET’s Disconnected Model An advantage of using class DataSet is that it is disconnected – the

program does not need a persistent connection to the data source to work with data in a DataSet. Instead, the program connects to the data source to populate the DataSet (i.e., fill the DataSet’s DataTable’s with data), but disconnects from the data source immediately after retrieving the desired data,

The program then accesses and potentially manipulates the data stored in the DataSet.

The program operates on this local cache of data, rather than the original data in the data source.

If the program makes changes to the data in the DataSet that need to be permanently saved in the data source, the program reconnects to the data source to perform an update then disconnects promptly.

Thus the program does not require any active, persistent connection to the data source.

Page 8: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

8

Class SqlDataAdapter An object of class SqlDataAdapter (namespace

System.Data.SqlClient) connects to a SQL Server data source and executes SQL statements to both populate a DataSet and update the data source based on the current contents of a DataSet.

A SqlDataAdapter maintains a SqlConnection object that it opens and closes as needed to perform these operations using SqlCommands.

Page 9: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

9

Programming with ADO.NET:Extracting Information from a Database

In this part, we demonstrate how to connect to a database, query the database and display the result of the query.

The IDE provides visual programming tools and wizards that simplify accessing data in your projects. These tools establish database connections and create the ADO.NET objects necessary to view and manipulate the data through GUI controls.

The following application demonstrates how to connect to and manipulate a SQL Server Books database (Books.mdf) that contains information about published books and authors of these books.

Page 10: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

10

Displaying a Database Table in a DataGridView

This Windows application performs a simple query on the Books database that retrieves Authors table and displays the data in a DataGridView (a control from namespace System.Windows.Forms that can display a data source in a GUI).

First, we demonstrate how to connect to the Books database and include it as a data source in the application.

Once the Books database is established as a data source, we can display the data from the Authors table in a DataGridView simply by dragging and dropping items in the project’s Design view.

Page 11: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

11

Step 1: Creating the Project

Create a new project named DisplayTable. Change the Form name to DisplayTableForm and change

the source file name to DisplayTable. Then set the Form’s Text property to Display Table.

Page 12: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

12

Step 2: Adding a Data Source to the Project To interact with a data source (e.g., a database), we must add it to the project using

the Data Sources window, which lists that data that the project can access. Open the Data Sources window by selecting Data > Show Data Sources or by

clicking the tab New Data Source… to open the Data Source Configuration Wizard. This wizard guides you through connecting to a database and choosing the parts of the database you will want to access in your project.

Page 13: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

13

Step 3: Choosing the Data Source Type to Add to the Project

The first screen of the Data Source Configuration Wizard asks you to choose the data source type you wish to include in the project.

Select Database and click Next>

Page 14: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

14

Step 4: Adding a New Database Connection

You must next choose the connection that will be used to connect to the database (i.e., the actual source of the data).

Click New Connection… to open the Add Connection dialog.

If the Data Source is not set to Microsoft SQL Server Database File (SqlClient), click change… select Microsoft SQL Server Database File and click OK.

In the Add Connection dialog, click browse…, locate the Books.mdf database file on your computer, select it and click Open.

You can click Test Connection to verify that the IDE can connect to the database through SQL Server. Click OK to create the connection.

Page 15: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

15

Page 16: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

16

Step 5: Choosing the Books.mdf Data Connection

Now that you have created a connection to the Books.mdf database, you can select and use this connection to access the database.

Click Next> to set the connection, then click Yes when asked whether you want to move the database file to your project.

Page 17: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

17

Step 6: Saving the Connection String The next screen asks you whether you want to save the connection string to the

application configuration file. A connection string specifies the path to a database file on disk, as well as some

additional settings that determine how to access the database. Saving the connection string in a configuration file makes it easy to change the connection settings at a later time. Leave the default selections and click Next> to proceed.

Page 18: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

18

Step 7: Selecting the Database Objects to Include in the DataSet

The IDE retrieves information about the database and prompts you to select the database objects (i.e., parts of the database) you want your project to be able to access. Recall that programs typically access a database’s contents through a cache of the data, which is stored in a DataSet.

In response to your selections in this screen. The IDE will generate a class derived from System.Data.DataSet that is designed specifically to store data from the Books database.

Click the checkbox to the left of Tables to indicate that the custom DataSet should cache (i.e., locally store) the data from all the tables in the Books database – Authors, AuthorISBN and Titles.

You can also expand the Tables node to select specific tables. The other database objects listed do not contain any data in our sample Books

database. By default, the IDE names the DataSet BooksDataSet, though it is possible to

specify a different name in this screen. Finally, click Finish to complete the process of adding a data source to the project.

Page 19: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

19

Page 20: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

20

Step 8: Viewing the Data Source in the Data Sources Window

Notice that a BookDataSet node now appears in the Data Sources window with child nodes for each table in Books database – these nodes represent the DataTables of the BooksDataSet.

Expand the Authors node and you will see the table’s columns – the DataSet’s structure mimics that of the actual Books database.

Page 21: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

21

Page 22: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

22

Step 9: Viewing the Database in the Solution Explorer

Books.mdf is now listed in the Solution Explorer, indicating that the database is now part of this project.

In addition, the Solution Explorer now lists a new node named BooksDataSet.xsd which specifies the DataSet’s structure as an XML Schema document including the tables that comprise the DataSet and the relationships among them.

When we added the Books database as a data source, the IDE created the BooksDataSet.xsd file based on the structure of the Books database.

The IDE then generated class BooksDataSet from the schema (i.e., structure) described by the .xsd file.

Page 23: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

23

Page 24: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

24

Displaying the Authors Table Now that we have added the Books database a s a data source, we can display the

data from the database’s Authors table in our program. The IDE provides design tools that allow you to display data from a data source on

a Form writing any code. Simply drag and drop items from the Data Sources window onto a Form, and the IDE generates the GUI controls and code necessary to display the selected data source’s content.

To display the Authors table of the Books database, drag the Authors node from the Data Sources window to the Form.

The IDE generates two GUI controls that appear on the DisplayTableForm – authorsBindingnavigator and authorsDataGridView. The IDE also generates several additional non-visual components that appear in the component tray – the gray region below the Form in Design view. We use the IDE’s default names for these autogenerated components to show exactly what the IDE creates.

We briefly discuss the authorsBindingnavigator and authorsDataGridView controls here. Later we discuss all of the autogenerated components in detail and explains how the IDE uses these components to connect the GUI controls to the Authors table of the Books database.

Page 25: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

25

Page 26: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

26

DataGridView

A DataGridView displays data organized in rows and columns that correspond to the rows and columns of the underlying data source.

In this case, the DataGridView displays the data of the Authors table, so the control has columns named AuthorID, FirstName and Lastname.

In Design View, the control does not display any rows of actual data below the column headers. The data is retrieved from the database and displayed in the DataGridView only at runtime.

Execute the program. When the forms loads, the DataGridView contains four rows of data – one for each row of the Authors table.

Page 27: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

27

DataGridView

Page 28: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

28

BindingNavigator The strip of buttons below the title bar of the window is a

BindingNavigator, which enables user to browse and manipulate data displayed by another GUI control (in this case, a DataGridView) on the Form.

A BindingNavigator’s buttons resemble the controls on a CD or DVD player and allow you to move to the first row of data, the preceding row, the next row and the last row.

The control also displays the currently selected row number in a text box. You can use this text box to enter a number of a row that you want to select.

The authorsBindingNavigator in this example allows you to “navigate” the Authors table displayed in the authorsDataGridView. Clicking the buttons or entering a value in the text box causes the DataGridView to select the appropriate row. An arrow in the DataGridView’s leftmost column indicates the currently selected row.

Page 29: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

29

How Data Binding Works

The technique through which GUI controls are connected to data sources is known as data binding. The IDE allows controls, such as a DataGridView, to be bound to a data source, such as a DataSet that represents a table in database.

Any changes you make through the application to the underlying data source will automatically be reflected in the way the data is presented in the data-bound control (e.g., the DataGridView).

Likewise, modifying the data in the data-bound control and saving the changes updates the underlying data source.

In the current example, the DataGridView is bound to the DataTable of the BooksDataSet that represents the Authors table in the database. Dragging the Authors node from the Data Sources window to the Form caused the IDE to create this data binding for you, using several autogenerated components (i.e., objects) in the component tray.

Page 30: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

30

How Data Binding Works

Page 31: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

31

BooksDataSet

Adding the Books database to the project enabled the IDE to generate the BooksDataSet. Recall that a DataSet represents a cache of data that mimics the structure of a relational database.

You can explore the structure of the BooksDataSet in the Data Sources window. A DataSet’s structure can be determined at execution time or at design time.

An untyped DataSet’s structure (i.e., the tables that comprise it and the relationships among them) is determined at execution time based on the result of a specific query. Tables and column values are accessed using indices into collections of DataTables and DataRows, respectively. The type of each piece of data in an untyped DataSet is unknown at design time.

BooksDataSet, however, is created by the IDE at design time as a strongly typed DataSet.

Page 32: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

32

BooksDataSet BooksDataSet (a derived class of DataSet) contains objects of classes derived

from DataTable that represent the tables in the Books database. BooksDataSet provides properties corresponding to the objects whose names match those of the underlying tables. For example, booksDataSet.Authors represents a cache of the data in the Authors table.

Each DataTable contains a collection of DataRows. Each DataRow contains members whose names and types correspond to those of the columns of the underlying table.

Thus, booksDataSet.Authors[0].AuthorID refers to the AuthorID of the first row of the Authors table in the Books database. Note that zero-based indices are used to access DataRows in a DataTable.

The booksDataSet object in the component tray is an object of the BooksDataSet class. When you indicate that you want to display the contents of the Authors table on the Form, the IDE generates a BooksDataSet object to store the data that Form will display. This is the data to which the DataGridView will be bound.

The DataGridView does not display data from the database directly. Instead, it displays the contents of a BooksDataSet object. The AuthorsTableAdapter fills the BooksDataSet object with data retrieved from the database by executing a SQL query.

Page 33: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

33

AuthorsTableAdapter The AuthorTableAdapter is the component that interacts with the Books database

on disk (i.e., the Books.mdf file). When other components need to retrieve data from the database or write data to the

database, they invoke the methods of the AuthorsTableAdapter. Class AuthorsTableAdapter is generated by the IDE when you drag a table from

the Books database onto the Form. The authorsTableAdapter object in the component tray is an object of this class.

The AuthorsTableAdapter is responsible for filling the BooksDataSet with the Authors data from the database – this stores a copy of the Authors table in local memory. This cached copy can be modified during program execution. Thus, the AuthorsTableAdapter is also responsible for updating the database when the data in the BooksDataSet changes.

Class AuthorsTableAdapter encapsulate a SqlDataAdapter object, which contains SqlCommand objects that specify how the SqlDataAdapter selects, inserts, updates and deletes data in the database. Recall that SqlCommand object must have a SqlConnection object through which the SqlCommand can communicate with a database. In this example, the AuthorsTableAdapter sets the Connection property of each of the SqlDataAdapter’s SqlCommand objects, based on the connection string that refers to the Books database.

Page 34: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

34

AuthorsTableAdapter

To interact with the database, the AuthorsTableAdapter invokes the methods of its SqlDataAdapter, each of which executes the appropriate SqlCommand object.

For example, to fill the BooksDataSet’s Authors table, the AuthorsTableAdapter’s Fill method invokes its SqlDataAdapter’s Fill method, which executes a SqlCommand object representing the SELECT query:

SELECT AuthorID, FirstName, LastName FROM Authors

This query selects all the rows and columns of the Authors table and places them in booksDataSet.Authors.

Page 35: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

35

authorsBindingSource and authorsDataGridView

The authorsBindingSource object (an object of class BindingSource) identifies a data source that a program can bind to a control and serves as an intermediary between a data-bound GUI control and its data source.

In this example, the IDE uses a BindingSource object to connect the authorsDataGridView to booksDataSet.Authors. To achieve this data binding, the IDE first sets authorsBindingSource’s DataSource property to BooksDataSet. This property specifies the DataSet that contains the data to be bound.

The IDE then sets the DataMember property to Authors. This property identifies a specific table within the DataSource.

After configuring the authorsBindingSource object, the IDE assigns this object to authorsDataGridView’s DataSource property to indicate what the DataGridView will display.

Page 36: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

36

authorsBindingSource and authorsDataGridView

A BindingSource object also manages the interaction between a data-bound GUI control and its underlying data source. If you edit the data displayed in a DataGridView and want to save changes to the data source, your code must invoke the EndEdit method of the BindingSource object.

This method applies the changes made to the data through the GUI control (i.e., the pending changes) to the data source bound to that control.

Note that this updates only the DataSet – an additional step is required to permanently update the database itself.

Page 37: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

37

authorsBindingNavigator A BindingNavigator allows you to move through (i.e., navigate) and

manipulate (i.e., add or delete rows) data bound to a control on a Form. A BindingNavigator communicates with a BindingSource (specified in the BindingNavigator’s BindingSource property) to carry out these actions in the underlying data source (i.e., the DataSet).

The BindingNavigator does not interact with the data-bound control. Instead, it invokes BindingSource methods that cause the data-bound control to update its presentation of the data. For example, when you click the BindingNavigator’s button to add a new row, the BindingNavigator invokes a method of the BindingSource. The BindingSource then adds a new row to its associated DataSet.

Once this DataSet is modified, the DataGridView displays the new row, because the DataGridView and the BindingNavigator are bound to the same BindingSource object (and thus the same DataSet).

Page 38: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

38

Examining the Autogenerated Code for DisplayTableForm

The code for DisplayTableForm is shown below. Note that you do not need to write any of this code – the IDE generates it when you drag and drop the Authors table from the Data Sources window onto the Form.

The IDE also generates a considerable amount of additional code, such as the code that defines classes BooksDataSet and AuthorsTableAdapter, as well as the designer code that declares the autogenerated objects in the component tray. the additional IDE-generated code resides in files visible in the Solution Explorer when you select Show All Files. We present only the code in DisplayTable.cs, because it is the only file you’ll need to modify.

Page 39: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

39

1. // DisplayTable.cs

2. // Display data from a database table in a DataGridView

3. using System;

4. using System.Windows.Forms;

5.

6. namespace DisplayTable

7. {

8. public partial class DisplayTableForm : Form

9. {

10. public DisplayTableForm()

11. {

12. InitializeComponent();

13. } // end constructor

14.

15. // Click event handler for the Save button in the

16. // BindingNavigator saves the changes made to the data

17. private void authorsBindingNavigatorSaveItem_Click(

18.

Page 40: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

40

18. object sender, EventArgs e)

19. {

20. this.Validate();

21. this.authorsBindingSource.EndEdit();

22. this.authorsTableAdapter.Update(this.booksDataSet.Authors);

23. }

24.

25. // loads data into the booksDataSet.Authors table,

26. // which is then displayed in the DataGridView

27. private void DisplayTableForm_Load(object sender, EventArgs e)

28. {

29. // TODO: This line of code loads data into the

30. // 'booksDataSet.Authors' table. You can move, or remove it,

31. // as needed.

32. this.authorsTableAdapter.Fill(this.booksDataSet.Authors);

33. } // end method DisplayTableForm_Load

34. } // end class DisplayTableForm

35. } // end namespace DisplayTable

Page 41: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

41

Examining the Autogenerated Code for DisplayTableForm

Lines 17-23 contain the Click event handler for the Save button to save changes made to the data in the DataGridView in the underlying data source (i.e., the Authors table of the Books database). Saving the changes is a two-step process:

1. The DataSet associated with the DataGridView (indicated by its BindingSource) must be updated to include any changes made by the user.

2. The database on disk must be updated to match the new contents of the DataSet.

Before the event handler saves any changes, line 21 invokes this.Validate() to validate the controls on the Form. If you implement Validating or Validated events for any of Form’s controls, these events enable you to validate user input and potentially indicate errors for invalid data.

Page 42: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

42

Examining the Autogenerated Code for DisplayTableForm

Lines 17-23 contain the Click event handler for the Save button to save changes made to the data in the DataGridView in the underlying data source (i.e., the Authors table of the Books database). Saving the changes is a two-step process:

1. The DataSet associated with the DataGridView (indicated by its BindingSource) must be updated to include any changes made by the user.

2. The database on disk must be updated to match the new contents of the DataSet.

Before the event handler saves any changes, line 21 invokes this.Validate() to validate the controls on the Form. If you implement Validating or Validated events for any of Form’s controls, these events enable you to validate user input and potentially indicate errors for invalid data.

Page 43: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

43

Examining the Autogenerated Code for DisplayTableForm

Line 21 invokes authorsBindingSource’s EndEdit method to ensure that the object’s associated data source (booksDataSet.Authors) is updated with any changes made by the user to the currently selected row in the DataGridView (e.g., adding a row, changing a column value). Any changes to other rows were applied to the method to write the modified version of the Authors table (in memory) to the SQL Server database on disk.

The Update method executes the SQL statements (encapsulated in SqlCommand objects) necessary to make the database’s Authors table match booksDataSet.Authors.

The Load event handler for DisplayTableForm (lines 27-33) executes when the program loads. This event handler fills the in-memory DataSet with data from the SQL Server database on disk. Once the DataSet is filled, the GUI control bound to it can display its data.

Page 44: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

44

Examining the Autogenerated Code for DisplayTableForm

Line 32 calls authorsTableAdapter’s Fill method to retrieve information from the database, placing this information in the DataSet member provided as an argument. Recall that authorsTableAdapter was generated by the IDE to execute SqlCommands over the connection we created within the Data Source Configuration Wizard.

Thus, the Fill method here executes a SELECT statement to retrieve all the rows of the Authors table of the Books database, then places the result of this query in booksDataSet.Authors.

Recall that authorsDataGridView’s DataSource property is set to authorsBindingSource (which references booksDataSet.Authors).

Thus, after this data source is loaded, the authorsDataGridView automatically displays the data retrieved from the database.

Page 45: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

45

Querying the Database

Now that we have seen how to display an entire database table in a DataGridView, we demonstrate how to execute specific SQL SELECT queries on a database and display the results.

Although this example only queries the data, the application could be modified easily to execute other SQL statements.

Perform the following steps to build the example application, which executes custom queries against the Titles table of the Books database.

Page 46: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

46

Step 1: Creating the Project

Create a new Windows Application named DisplayQueryResult. Rename the Form DisplayQueryResultForm and name its source file DisplayQueryResult.cs, then set the Form’s Text property to Display Query Result.

Page 47: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

47

Step 2: Adding a Database Source to the Project

Perform the steps that we have done in the previous example to include the Books database as a data source in the project.

Page 48: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

48

Step 3: Creating a DataGridView to Display the Titles Table

Drag the Titles node from the Data Sources window onto the Form to create a DataGridView that will display the entire contents of the Titles table.

Page 49: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

49

Step 4: Adding Custom Queries to the TitlesTableAdapter Recall that invoking a TableAdapter’s Fill method populates the DataSet passed

as an argument with the entire contents of the database table that corresponds to that TableAdapter.

To populate a DataSet member (i.e., a DataTable) with only a portion of a table (e.g., books with copyright dates of 2006), you must add a method to the TableAdapter that fills the specified DataTable with the results of a custom query. The IDE provides the TableAdapter Query Configuration Wizard to perform this task.

To open this wizard, first right click the BooksDataSet.xsd node in the Solution Explorer and choose View Designer. You can also click the Edit DataSet with Designer icon.

Either of these actions opens the DataSet Designer which displays a visual representation of the BooksDataSet (i.e., the tables AuthorISBN, Authors and Titles and the relationships among them).

The DataSet Designer lists each table’s columns and the autogenerated TableAdapter that accesses the table.

Select the TitlesTableAdapter by clicking its name, then right click the name and select Add Query… to begin the TableAdapter Query Configuration Wizard.

Page 50: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

50

Page 51: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

51

Step 5: Choosing How the TableAdapter Should Access the Database

On the next screen of the wizard keep the default option Use SQL Statements and click Next.

Page 52: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

52

Step 6: Choosing a Query Type

On the next screen of the wizard keep the default option SELECT which returns rows and click Next.

Page 53: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

53

Step 7: Specifying a SELECT Statement for the Query

The next screen asks you to enter a query that will be used to retrieve data from the Books database. Note that the default SELECT prefixes Titles with “dbo.”. This prefix stands for “database owner” and indicates that the table Titles belongs to the database owner (i.e., you). In cases where you need to reference a table owned by another user of the system, this prefix would be replaced by the owner’s username. You can modify the SQL statement in the text box here, or you can click Query Builder… to design and test the query using a visual tool.

Page 54: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

54

Step 8: Builder a Query with Query Builder

Click the Query Builder… button to open the Query Builder. The top portion of the Query Builder window contains a box listing the columns of the Titles table.

By default, each columns is checked, indicating that each column should be returned by the query. The middle portion of the window contains a table in which each row corresponds to a column in the Titles table. To the right of the column names are columns in which you can enter values or make selections to modify the query.

For example, to create a query that selects only books that are copyright 2006, enter the value 2006 in the Filter column of the Copyright row. Note that the Query Builder modifies your input to be “=‘2006’” and adds an appropriate WHERE clause to the SELECT statement displayed in the middle.

Click the Execute Query button to test the query and display the results in the bottom portion of the Query Builder window.

Page 55: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

55

Page 56: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

56

Page 57: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

57

Step 9: Closing the Query Builder

Click OK to close the Query Builder and return to the TableAdapter Query Configuration Wizard, which now displays the SQL query created in the preceding step. Click Next to continue.

Page 58: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

58

Step 10: Setting the Names of the Autogenerated Methods That Perform the Query

After you specify the SQL query, you must name the methods that the IDE will generate to perform the query. Two methods are generated by default – a “Fill method” that fills a DataTable parameter with the query result and a “Get method” that returns a new DataTable filled with the query result.

The text boxes to enter names for these methods are prepopulated with FillBy and GetDataBy, respectively. Modify these names to FillWithCopyright2006 and GetDataWithCopyright2006.

Finally, click Finish to complete the wizard and return to the Dataset Designer.

Note that these methods are now listed in the TitlesTableAdapter section of the box representing the Titles table.

Page 59: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

59

Page 60: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

60

Step 11: Adding an Additional Query

Repeat Steps 4-10 to add another query that selects all books whose titles end with the text “How to Program” and sorts the results by title in ascending order.

In the Query Builder, enter LIKE ‘%How to Program’ in the Title row’s Filter column.

To specify the sort order, select Ascending in the Sort Type column of the Title row.

In the final step of the TableAdapter Query Configuration Wizard, name the Fill and Get methods FillWithHowToProgramBooks and GetDataForHowToProgramBooks, respectively.

Page 61: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

61

Step 12: Adding a ComboBox to the Form

Return to Design view and add below the DataGridView a ComboBox named queriesComboBox to the Form. Users will use this control to choose a SELECT query to execute, whose result will be displayed in the DataGridView.

Add three items to queriesComboBox – one to match each of the three queries that the TitlesTableAdapter can now perform:

SELECT ISBN, Title, EditionNumber, Copyright FROM Titles

SELECT ISBN, Title, EditionNumber, Copyright FROM Titles

WHERE (Copyright = ‘2006’)

SELECT ISBN, Title, EditionNumber, Copyright FROM Titles

WHERE (Title LIKE ‘%How to Program’) ORDER BY Title

Page 62: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

62

Step 13: Customizing the Form’s Load Event Handler

Add a line of code to the autogenerated DisplayQueryResultForm_Load event handler, which sets the initial SelectedIndex of the queriesComboBox to 0.

Recall that the Load event handler calls the Fill method by default, which executes the first query (the item in index 0).

Thus, setting the SelectedIndex causes the ComboBox to display the query that is initially performed when DisplayQueryResultForm first loads.

Page 63: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

63

Step 14: Programming an Event for the ComboBox

Next you must write code that will execute the appropriate query each time the user chooses a different item from queriesComboBox.

Double click queriesComboBox in Design view to generate a queriesComboBox_SelectedIndexChanged event handler (lines 42-61) in the DisplayQueryResult.cs file. Then to the event handler add a switch statement that invokes the method of titlesTableAdapter that executes the query associated with the ComboBox’s current selection (lines 47-60). Recall that method Fill (line 50) executes a SELECT query that selects all rows, method FillWithCopyright2006 (lines 53-54) executes a SELECT query that selects all rows in which the copyright year is 2006 and method FillWithHowToProgramBooks (lines 57-58) executes a query that selects all rows that have “How to Program” at the end of their titles and sorts them in ascending order by title. Each method fills BooksDataSet.Tltles with only those rows returned by the corresponding query. Thanks to the data binding relationship created by the IDE, refilling booksDataSet.Titles causes the TitlesDataGridView to display the selected query’s result with no additional code.

Page 64: Connecting to Data Sources Using ADO.NET Dr. Awad Khalil Computer Science & Engineering Department AUC

Introduction to the Internet & WWW by Dr. Khalil

64