Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

The DataAdapter

In Chapter 2, you looked at the DataSet as a collection of DataTable objects. You used the DataTables in the DataSet to populate one or more server controls on an ASP.NET Web Form. The DataAdapter is the bridge between the DataSet and the data store.

Unlike the past model of connection-based data processing, the DataAdapter works on a disconnected message-based model, revolving around and delivering chunks of information in a disconnected fashion. The DataAdapter is made up of four command methods, a TableMappings collection, a Command collection, and an Exception collection (for OleDbErrors). Like the other objects in the Managed Providers, the DataAdapter comes in two stock flavors, the SqlDataAdapter and the OleDbDataAdapter. Figure 3.4 illustrates the DataAdapter Object Model.

Figure 3.4 The DataAdapter Object Model

The primary function of a DataAdapter is to retrieve data from a data store and push it into a DataTable in the DataSet. To complete this task, the DataAdapter requires two pieces of information, or parameters:

  • A Managed Connection

  • A Select Command

The DataAdapter constructor can accept either the command and connection values as text, or a Managed Command object as a single parameter. Listing 3.8 demonstrated constructing a DataAdapter with text values, while Listing 3.9 demonstrates constructing the DataAdapter with a single Managed Command.

Listing 3.8 Creating a SqlDataAdapter with Connection and Command Text Values

[VB]

01: <%@ Page Language="VB" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: Sub Page_Load(Sender As Object, E As EventArgs)
06:  Dim myDataAdapter As SqlDataAdapter
07:  Dim myDataSet As New DataSet
08:  myDataAdapter = New SqlDataAdapter("SELECT * FROM Customers",
   "server=localhost; database=Northwind; uid=sa; pwd=;")
09:  myDataAdapter.Fill(myDataSet, "Customers")
10:  myDataGrid.DataSource = myDataSet.Tables("Customers").DefaultView
11:  myDataGrid.DataBind()
12: End Sub
13: </script>

[C#]

01: <%@ Page Language="C#" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: void Page_Load(Object sender, EventArgs e){
06:  SqlDataAdapter myDataAdapter;
07:  DataSet myDataSet = new DataSet();
08:  myDataAdapter = new SqlDataAdapter("SELECT * FROM Customers",
   "server=localhost; database=Northwind; uid=sa; pwd=;");
09:  myDataAdapter.Fill(myDataSet, "Customers");
10:  myDataGrid.DataSource = myDataSet.Tables["Customers"].DefaultView;
11:  myDataGrid.DataBind();
12: }
13: </script>

[VB & C#]

14: <html>
15: <form runat="server" method="post">
16: <body>
17: <asp:DataGrid runat="server" id="myDataGrid" />
18: </form>
19: </body>
20: </html>

In Listing 3.8 you create an instance of the SqlDataAdapter class. When instantiating the class, on line 08 you pass in the command and connection values as text. The DataAdapter uses these values to create SqlCommand and SqlConnection objects behind the scenes. These objects are used to connect to the database and retrieve the appropriate data.

In Listing 3.9 you achieve the same result as in Listing 3.8, using explicit SqlCommand and SqlConnection objects.

Listing 3.9 Creating an SqlDataAdapter with Connection and Command Objects

[VB]

01: <%@ Page Language="VB" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: Sub Page_Load(Sender As Object, E As EventArgs)
06:  Dim myConnection As SqlConnection
07:  Dim myCommand As SqlCommand
08:  Dim myDataAdapter As SqlDataAdapter
09:  Dim myDataSet As New DataSet
10:  myConnection = New SqlConnection("server=localhost; database=Northwind; uid=sa; pwd=;")
11:  myCommand = New SqlCommand("SELECT * FROM Customers", myConnection)
12:  myDataAdapter = New SqlDataAdapter(myCommand)
13:  myDataAdapter.Fill(myDataSet, "Customers")
14:  myDataGrid.DataSource = myDataSet.Tables("Customers").DefaultView
15:  myDataGrid.DataBind()
16: End Sub
17: </script>

[C#]

01: <%@ Page Language="C#" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: void Page_Load(Object sender, EventArgs e){
06:  SqlConnection myConnection;
07:  SqlCommand myCommand;
08:  SqlDataAdapter myDataAdapter;
09:  DataSet myDataSet = new DataSet();
10:  myConnection = new SqlConnection("server=localhost; database=Northwind; uid=sa; pwd=;");
11:  myCommand = new SqlCommand("SELECT * FROM Customers", myConnection);
12:  myDataAdapter = new SqlDataAdapter(myCommand);
13:  myDataAdapter.Fill(myDataSet, "Customers");
14:  myDataGrid.DataSource = myDataSet.Tables["Customers"].DefaultView;
15:  myDataGrid.DataBind();
16: }
17: </script>

[VB & C#]

18: <html>
19: <form runat="server" method="post">
20: <body>
21: <asp:DataGrid runat="server" id="myDataGrid" />
22: </form>
23: </body>
24: </html>

In Listing 3.9 you explicitly create SqlCommand and SqlConnection objects. The SqlConnection object is used when constructing the SqlCommand object, and the SqlCommand object is passed into the SqlDataAdapter when it is instantiated.

While this may seem logical, it is more efficient to create the DataAdapter using the text values. The DataAdapter will manage the creation and destruction of the connection and command objects it requires. The explicit creation of these objects is only useful if you will be using either or both of them again, separate of the DataAdapter.

DataAdapter.Fill() Method

In Listings 3..8[ed]3.9, you used various techniques and languages to create an instance of the Managed Provider DataAdapter. In one fashion or another, you created the DataAdapter and passed it values for the the SelectCommand and Connection properties (either as inline values or as objects). Once the DataAdapter was created, the Fill() method of the DataAdapter was called.

The DataAdapter.Fill() method is like the switch that makes it go. Up until the Fill() method is called, the DataAdapter is idle. When the Fill() method is called, the connection to the database is made, and the SQL statement is executed. The results from the execution are filled into a DataSet, specified as a parameter of the Fill() method.

Specifying only a DataSet to fill the result set into will cause a new DataTable object to be created in the DataSet. The DataTable is then accessible by its index value.

DataAdapter.Fill([DataSet])
DataGrid.DataSource = DataSet.Tables(0).DefaultView

Optionally, you can also pass in a string value representing the name you would like assigned to the DataTable that is created. This makes your code easier to follow and more readable, as you can then access the DataTable by name rather than by its index value.

DataAdapter.Fill([DataSet], "[Table Name]")
DataGrid.DataSource = DataSet.Tables("[Table Name]").DefaultView

On line 13 of Listing 3.9 you invoke the Fill() method of the DataAdapter and fill the results of the executed SQL statement into an empty DataSet, creating a new DataTable named "Customers".

When the Fill() method is invoked, the bridge to the data store is extended. Then the data is retrieved and brought back to the calling application in the form of an XML file. This XML file is materialized as a DataTable in the DataSet you specified. The DataTable schema (table/column/primary key definitions) will be created automatically based on the schema of the database. Figure 3.5 illustrates the process when you're invoking the DataAdapter.Fill() method.

Figure 3.5 Invoking the Fill() method of the DataAdapter class causes a bridge to be extended to the data store and the results to be returned to the calling application in the form of an XML file. The XML file is materialized as a DataTable in a DataSet.

While the Fill() method will create the DataTable dynamically, it can also fill an existing DataTable that you create explicitly, as shown in Listing 3.10.

Listing 3.14 Using the DataAdapter with an Existing DataTable

[VB]

01: <%@ Page Language="VB" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: Sub Page_Load(Sender As Object, E As EventArgs)
06:  Dim myDataAdapter As SqlDataAdapter
07:  Dim myDataSet As New DataSet
08:
09:  myDataSet.Tables.Add(New DataTable("Customers"))
10:  myDataSet.Tables("Customers").Columns.Add("CompanyName",
   System.Type.GetType("System.String"))
11:  myDataSet.Tables("Customers").Columns.Add("ContactName",
   System.Type.GetType("System.String"))
12:  myDataSet.Tables("Customers").Columns.Add("Region",
   System.Type.GetType("System.String"))
13:
14:  myDataAdapter = New SqlDataAdapter("SELECT
   CompanyName, ContactName, Region FROM Customers",
   "server=localhost; database=Northwind; uid=sa; pwd=;")
15:  myDataAdapter.Fill(myDataSet, "Customers")
16:  myDataGrid.DataSource = myDataSet.Tables("Customers").DefaultView
17:  myDataGrid.DataBind()
18: End Sub
19: </script>

[C#]

01: <%@ Page Language="C#" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: void Page_Load(Object sender, EventArgs e){
06:  SqlDataAdapter myDataAdapter;
07:  DataSet myDataSet = new DataSet();
08:
09:  myDataSet.Tables.Add(new DataTable("Customers"));
10:  myDataSet.Tables["Customers"].Columns.Add("CompanyName",
   System.Type.GetType("System.String"));
11:  myDataSet.Tables["Customers"].Columns.Add("ContactName",
   System.Type.GetType("System.String"));
12:  myDataSet.Tables["Customers"].Columns.Add("Region",
   System.Type.GetType("System.String"));
13:
14:  myDataAdapter = new SqlDataAdapter("SELECT
   CompanyName, ContactName, Region FROM Customers",
   "server=localhost; database=Northwind; uid=sa; pwd=;");
15:  myDataAdapter.Fill(myDataSet, "Customers");
16:  myDataGrid.DataSource = myDataSet.Tables["Customers"].DefaultView;
17:  myDataGrid.DataBind();
18: }
19: </script>

[VB & C#]

20: <html>
21: <form runat="server" method="post">
22: <body>
23: <asp:DataGrid runat="server" id="myDataGrid" />
24: </form>
25: </body>
26: </html>

In Listing 3.10 you create a DataTable explicitly on lines 09[ed]12. Using the Fill() method of the DataAdapter you fill this newly created DataTable with the results from the SQL statement execution. This is done by calling the Fill() method and passing in the DataSet and DataTable name for the DataTable you just created. If data already exists in the DataTable, then the Fill() method will update, or add rows to the DataTable. You can use the same DataAdapter, change its SelectCommand.CommandText property, and invoke the Fill() method again. In Listing 3.11 you use the DataAdapter to return two different result sets from similar SQL statements. You use the Fill() method to add the records to the same DataTable in the DataSet.

Listing 3.11 Using the Fill() Method to Add Records to a DataTable

[VB]

01: <%@ Page Language="VB" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: Sub Page_Load(Sender As Object, E As EventArgs)
06:  Dim myDataAdapter As SqlDataAdapter
07:  Dim myDataSet As New DataSet
08:
09:  myDataSet.Tables.Add(New DataTable("Customers"))
10:  myDataSet.Tables("Customers").Columns.Add("CompanyName",
   System.Type.GetType("System.String"))
11:  myDataSet.Tables("Customers").Columns.Add("ContactName",
   System.Type.GetType("System.String"))
12:  myDataSet.Tables("Customers").Columns.Add("Region",
   System.Type.GetType("System.String"))
13:
14:  myDataAdapter = new SqlDataAdapter("SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='BC'",
   "server=localhost; database=Northwind; uid=sa; pwd=;")
15:  myDataAdapter.Fill(myDataSet, "Customers")
16:
17:  myDataAdapter.SelectCommand.CommandText = "SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='SP'"
18:  myDataAdapter.Fill(myDataSet, "Customers")
19:
20:  myDataGrid.DataSource = myDataSet.Tables("Customers").DefaultView
21:  myDataGrid.DataBind()
22: End Sub
23: </script>

[C#]

01: <%@ Page Language="C#" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: void Page_Load(Object sender, EventArgs e){
06:  SqlDataAdapter myDataAdapter;
07:  DataSet myDataSet = new DataSet();
08:
09:  myDataSet.Tables.Add(new DataTable("Customers"));
10:  myDataSet.Tables["Customers"].Columns.Add("CompanyName",
   System.Type.GetType("System.String"));
11:  myDataSet.Tables["Customers"].Columns.Add("ContactName",
   System.Type.GetType("System.String"));
12:  myDataSet.Tables["Customers"].Columns.Add("Region",
   System.Type.GetType("System.String"));
13:
14:  myDataAdapter = new SqlDataAdapter("SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='BC'",
   "server=localhost; database=Northwind; uid=sa; pwd=;");
15:  myDataAdapter.Fill(myDataSet, "Customers");
16:
17:  myDataAdapter.SelectCommand.CommandText = "SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='SP'";
18:  myDataAdapter.Fill(myDataSet, "Customers");
19:
20:  myDataGrid.DataSource = myDataSet.Tables["Customers"].DefaultView;
21:  myDataGrid.DataBind();
22: }
23: </script>

[VB & C#]

24: <html>
25: <form runat="server" method="post">
26: <body>
27: <asp:DataGrid runat="server" id="myDataGrid" />
28: </form>
29: </body>
30: </html>

In Listing 3.11 you use the DataAdapter to select a small set of records from the database (line 14). Using the Fill() method you add those records to the Customers DataTable on line15. On line 17 you change the SelectCommand.CommandText property of the DataAdapter to use a new criteria when executing the SQL statement on the database. Since the DataAdapter was constructed with a ConnectionString property you do not need set it. The only exception to this is if you are going to use the same DataReader to connect to a different database. If that is the case, you would set the DataAdapter. SelectCommand.ConnectionString property to a new, valid connection string. Using the Fill() method, on line 18, you add the new result set to the existing records in the Customers table. Figure 3.6 shows the result of executing the code in Listing 3.11.

Figure 3.6 The DataAdapter. Fill() method can be used to add records to a DataTable, or update existing records.

As you've learned, the DataAdapter works on a disconnected message-based model. You can reuse the DataAdapter to fill additional DataTables in the same DataSet, or in other DataSets, because there's no physical link between the DataAdapter and the DataSet or DataTable. You only need to change the SelectCommand property of the DataSet (if you want to use a new SQL statement), and call the Fill() method, passing it the new DataSet and DataTable name (see Listing 3.12).

Listing 3.12 Adding a Second DataTable to a DataSet

[VB]

01: <%@ Page Language="VB" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: Sub Page_Load(Sender As Object, E As EventArgs)
06:  Dim myDataAdapter As SqlDataAdapter
07:  Dim myDataSet As New DataSet
08:
09:  myDataAdapter = new SqlDataAdapter("SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='BC'",
   "server=localhost; database=Northwind; uid=sa; pwd=;")
10:  myDataAdapter.Fill(myDataSet, "BC_Customers")
11:
12:  myDataAdapter.SelectCommand.CommandText = "SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='SP'"
13:  myDataAdapter.Fill(myDataSet, "SP_Customers")
14:
15:  myDataGrid.DataSource = myDataSet.Tables("BC_Customers").DefaultView
16:  myDataGrid.DataBind()
17:
18:  myOtherDataGrid.DataSource = myDataSet.Tables("SP_Customers").DefaultView
19:  myOtherDataGrid.DataBind()
20: End Sub
21: </script>

[C#]

01: <%@ Page Language="C#" %>
02: <%@ Import Namespace="System.Data" %>
03: <%@ Import Namespace="System.Data.SqlClient" %>
04: <script runat="server">
05: void Page_Load(Object sender, EventArgs e){
06:  SqlDataAdapter myDataAdapter;
07:  DataSet myDataSet = new DataSet();
08:
09:  myDataAdapter = new SqlDataAdapter("SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='BC'",
   "server=localhost; database=Northwind; uid=sa; pwd=;");
10:  myDataAdapter.Fill(myDataSet, "BC_Customers");
11:
12:  myDataAdapter.SelectCommand.CommandText = "SELECT CompanyName,
   ContactName, Region FROM Customers WHERE Region='SP'";
13:  myDataAdapter.Fill(myDataSet, "SP_Customers");
14:
15:  myDataGrid.DataSource = myDataSet.Tables["BC_Customers"].DefaultView;
16:  myDataGrid.DataBind();
17:
18:  myOtherDataGrid.DataSource =
   myDataSet.Tables["SP_Customers"].DefaultView;
19:  myOtherDataGrid.DataBind();
20: }
21: </script>

[VB & C#]

22: <html>
23: <form runat="server" method="post">
24: <body>
25: <asp:DataGrid runat="server" id="myDataGrid" />
26: <asp:DataGrid runat="server" id="myOtherDataGrid" />
27: </form>
28: </body>
29: </html>

In Listing 3.12 you use the DataAdapter to select a limited set of data from the database using a WHERE clause. You use the Fill() method to create a new DataTable named BC_Customers. Then, by resetting the SelectCommand.CommandText you retrieve another limited set of data from the database. Using the Fill() method you create a second DataTable named SP_Customers. Finally you bind each of these DataTables to a separate DataGrid. The resulting page is shown in Figure 3.7.

Figure 3.7 The DataAdapter can be used to create multiple DataTables in one or more DataSets. This is allowed because the DataAdapter is not explicitly tied to a single DataSet or DataTable.

  • + Share This
  • 🔖 Save To Your Account