Tải bản đầy đủ (.pdf) (56 trang)

Module 3: Using ADO.NET to Access Data

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.02 MB, 56 trang )








Contents
Overview 1
Overview of ADO.NET 2
Connecting to a Data Source 10
Accessing Data With DataSets 12
Using Stored Procedures 28
Accessing Data with DataReaders 37
Binding to XML Data 44
Lab 3: Using ADO.NET to Access Data 49
Review 50

Module 3: Using
ADO.NET to Access
Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.



Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

 2000 Microsoft Corporation. All rights reserved.

Microsoft, BackOffice, MS-DOS, Windows, Windows NT, <plus other appropriate product
names or titles. The publications specialist replaces this example list with the list of trademarks
provided by the copy editor. Microsoft is listed first, followed by all other Microsoft trademarks
in alphabetical order. > are either registered trademarks or trademarks of Microsoft Corporation
in the U.S.A. and/or other countries.

<The publications specialist inserts mention of specific, contractually obligated to, third-party
trademarks, provided by the copy editor>

Other product and company names mentioned herein may be the trademarks of their respective
owners.


Module 3: Using ADO.NET to Access Data iii

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Instructor Notes
One of the reasons for the widespread use of ASP was its easy access to data
stores. ASP.NET extends this feature with the introduction of ADO.NET.
This module focuses on using ADO.NET for accessing data from various data
sources. Students also learn how to display data and customize the display of

data.
In the lab, students will connect to a database, fill a DataSet, and customize the
data display by using a Repeater control.
After completing this module, students will be able to:
!
Describe the ADO.NET object model.
!
Connect to a data source using ADO.NET.
!
Retrieve data from a database using DataReaders, and DataSets.
!
Display the data from a database on the client using list-bound controls.
!
Customize the look of a Repeater control with templates.
!
Use stored procedures to return RecordSets.
!
Read data from an XML file into a DataSet.

Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the following materials:
!
Microsoft
®
PowerPoint
®
file 2063A_03.ppt

!
Module 3, “Using ADO.NET to Access Data” (2063A_03.doc)
!
Lab 3, “Using ADO.NET to Access Data” (2063A_L03.doc)
!
Animation: “Using ADO.NET to Access Data” (2063A_03A001.swf)

Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Complete all the demonstrations.
!
Complete the lab.
!
Go through the animation.
!
Study material on the differences between ADO and ADO.NET.

Presentation:
180 Minutes

Lab:
30 Minutes
iv Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Multimedia Presentation

This section provides multimedia presentation procedures that do not fit in the
margin notes or are not appropriate for the student notes.
Using ADO.NET to Access Data
!
To present the animation
Action Say this

Before starting the animation, say this:
There are two ways of accessing data from a database using
ADO.NET; using DataSets or Using DataReaders. This animation
demonstrates how these methods work, and highlights the
differences between the two methods.
Click DataSet The DataSet method is a disconnected way of accessing data from a
database.
In this method, when a user requests for data from a database, the
DataSetCommand object is used to create a DataSet, which
basically is a collection of DataTables from the database and also
retains the relationships between these tables. Notice that once a
DataSet is populated, it is disconnected from the database.
In order to display the data from the DataSet, you set up a
DataView for the desired table. The DataView is then bound to a
list-bound control for displaying purposes. You can use any of the
three listbound controls, DataGrid, Repeater, or DataList in order to
display data.
The data in the listbound control is then displayed on the client.
An important point here is that the use of DataView to display data
is valid only in the Beta 1 and older versions of ASP.NET. From the
Beta 2 version onwards, you can directly bind your DataSet to a
listbound control.
Click DataReader This method is similar to the ADO way of accessing data using

recordsets.
In this method, when a user requests for data from a database, the
Command object retrieves the data into a DataReader. A
DataReader is a read-only/forward-only view on the data A
DataReader works similarly to a recordset in ADO, allowing you to
simply loop through the records. Like ADO recordsets,
DataReaders are connected to the database. You need to explicitly
close the connection when you are finished reading data.



Module 3: Using ADO.NET to Access Data v

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Module Strategy
Use the following strategy to present this module:
!
Overview of ADO.NET
This section provides students with an overview of ADO.NET. The section
begins with an animation on using ADO. After the animation has been
viewed, describe each of the objects shown in the model. Since students are
familiar with ADO, this is a good place discuss some of the main
differences between ADO and ADO.NET.
When talking about using namespaces, explain their significance to the
students.
!
Connecting to a Data Source
From this section onwards, students will actually start working with
ADO.NET. Tell them that all the examples in this module use

SQLConnection objects rather than ADOconnection objects. Mention that
using ADOConnection objects is very similar, and point them to the .NET
framework SDK. In some instances, you could demonstrate how the same
example would look using ADOConnection objects.
!
Accessing Data with DataSets
ADO.NET provides two ways of accessing data, using DataSets and
DataReaders. This section focuses on accessing data using DataSets.
DataSets represent a new concept, so spend additional time on this section.
The demonstration actually shows every aspect of data access with
ADO.NET. Go through the demonstration carefully, and make sure that the
students understand the details. There is also an exercise later in this section
that enables students to practice these concepts.
When talking about using templates with a Repeater control, do not spend
time delving into the details of these controls. Point students to the .NET
framework SDK for more information about these controls.
!
Using Stored Procedures
Most students, who have worked with the SQL database and ADO, will
have experience with using stored procedures. This section provides them
information on how to use stored procedures and parameterized stored
procedures with ADO.NET.
!
Accessing Data with DataReaders
This section focuses on accessing data using DataReaders. Make sure that
you point out to the students that when using DataReaders, the database
connection is always open. When they are finished reading data, they need
to explicitly close the connection.
!
Binding to XML Data

XML is fast emerging as the most popular language for exchanging data.
This section provides students with information on how to read XML data
using ADO.NET.
Most students will already know about XML documents. However, for
students who are not familiar with XML, it will be useful to show an
example of an XML document and how it is displayed on the client.


Module 3: Using ADO.NET to Access Data 1

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Overview
!
Overview of ADO.NET
!
Connecting to a Data Source
!
Accessing Data with DataSets
!
Using Stored Procedures
!
Accessing Data with DataReaders
!
Binding to XML Data


One of the reasons for the widespread use of ActiveX
®
Server Pages (ASP) was

that it facilitated access to data stores. ASP.NET extends this feature with the
introduction of ADO.NET, which offers a rich suite of data handling and data
binding functions for manipulating all types of data.
After completing this module, you will be able to:
!
Describe the ADO.NET object model.
!
Connect to a data source by using ADO.NET.
!
Retrieve data from a database by using DataReaders, and DataSets.
!
Display the data from a database on the client by using list-bound controls.
!
Customize the look of a Repeater control with templates.
!
Use stored procedures to return recordsets.
!
Read data from an XML file into a DataSet.

Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about the data binding
features in ASP.NET.
2 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY


# Overview of ADO.NET
!
Animation: Using ADO.NET to Access Data
!
The ADO.NET Object Model
!
RecordSets vs. DataSets
!
Using Namespaces


ADO.NET is not a revision of ADO, but a new way to manipulate data that is
based on disconnected data and XML. Although ADO is an important data
access tool with ASP, it does not provide all the necessary features for
developing robust and scalable Web applications. Despite ADO's rich object
model and relatively ease of use, it is connected by default, relies on an OLE
DB provider to access data, and is entirely COM based.
ADO.NET has been designed to work with disconnected data sets.
Disconnected sets of records are useful because they are local views of the data
that are faster to process and transmit, and they also reduce network traffic.
ADO.NET utilizes XML as the universal transmission format. This guarantees
interoperability as long as the receiving component runs on a platform where an
XML parser is available. When the transmission occurs through XML, it is no
longer necessary that the receiver be a COM object. The receiving component
has no architectural restrictions whatsoever. Any software component can share
ADO.NET data, as long as it agrees to use the same XML schema for the
format of the transmitted data.
In this section, you will learn about ADO.NET. You will learn about the new
and modified objects in ADO.NET. You will also learn about some of the new

namespaces that are included in ASP.NET.
Topic Objective
To introduce the topics
included in this section.
Lead-in
ASP.NET offers a new
means to retrieve the data
with the introduction of
ADO.NET.
Module 3: Using ADO.NET to Access Data 3

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Animation: Using ADO.NET to Access Data


In this animation, you will learn how to access data using
ADO.NET and how you can display that data in an ASP.NET
page. To view the animation, open the 2063A_03A001.swf file
from the Media folder.

Topic Objective
To provide a high-level
overview of how to access
data by using ADO.NET.
Lead-in
In this animation, you will
learn about how ADO.NET
accesses data and how you
can display that data in an

ASP.NET page.

Delivery Tip
Run the Macromedia Flash
animation Using ADO.NET
to Access Data.
(2063A_03A001.swf)

For details on how to run
and describe the animation,
see the Multimedia
Presentation section in the
Instructor Notes for this
module.

4 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

The ADO.NET Object Model
DataSetCommand
Connection
Database
Database
Command
.ASPX Page
List-Bound
Control
List-Bound
Control

DataReader
Company:
Northwind Traders
Company:
Northwind Traders
.ASPX Page
DataView
DataView
DataSet


ADO.NET evolved from the ADO data access model. ADO.NET allows you to
develop applications that are robust and scalable, and can use XML.
ADO.NET has some of the same objects as ADO (like the Connection and
Command objects), and introduces new objects such as DataSets,
DataReaders, and DatasetCommands.
Some of objects in ADO.NET represent updates of existing objects (such as
Connection and Command), while others are completely new (such as
DataReader, DataSet, DataView, and DataSetCommand.
Connection Objects
Connection objects are used to talk to databases. They have properties such as
dataSource, userID, and password that are needed to access a particular
datasource. Commands travel over connections and result sets are returned in
the form of streams, which can be read by DataReaders, or pushed into
DataSet objects.
Command Objects
Command objects contain the information that is submitted to a database. A
command can be a stored procedure call, an update statement, or a statement
that returns results. You can also use input and output parameters and return
values.

DataReader Objects
The DataReader is a read-only/forward-only view on the data. DataReaders
provide a simple and lightweight way of traversing through record sets. For
example, if you wanted to simply show the results of a search list in a web
page, using a DataReader is an ideal way to accomplish this.
Topic Objective
To describe the ADO.NET
object model.
Lead-in
ADO.NET has some of the
same objects as ADO (like
Connection and Command),
and introduces new objects
such as DataSets,
DataReaders and
DatasetCommands.
Module 3: Using ADO.NET to Access Data 5

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

DataReaders are returned after executing a command. They work similarly to a
recordset in ADO, allowing you to simply loop through the records.
ADO.NET includes two types of DataReaders: SQLDataReader for SQL
data, and ADODataReader for ADO data. The DataReader object is database
specific. The behavior for the SQLDataReader may differ from the behavior
for the ADODataReader, and other DataReaders that emerge in the future
You use the ADOCommand and SQLCommand objects, and the Execute
method to get data into a DataReader.
DataSet Objects
The DataSet is designed to handle the actual data from a data store. The

DataSet provides a rich object model to work with when passing data between
various components of an enterprise solution. The DataSet object is generic.
The behavior of a Dataset is completely consistent regardless of the underlying
database, SQL or ADO.
The DataSet object represents a cache of data, with database like behavior. It
contains tables, columns, relationships, constraints, and data. Data coming from
a database, an XML file, code, or user input can be entered into DataSet objects
and converted into files, forms, or databases. As changes are made to the
DataSet, they are tracked similar to tracking changes in a word processing
document.
The DataSet object has a collection of DataTable objects. A DataTable
represents one table of in-memory data. It contains a collection of columns that
represents the table's schema. A DataTable also contains a collection of rows,
representing the data contained in the table.
You use the ADODataSetCommand and SQLDataSetCommand objects and
the FillDataSet method to get data into DataSets.
DataView Objects
DataView provides a custom view of a data table. You can think of the
DataView as the equivalent of the ADO disconnected recordset, as it contains a
single view on top of the table data. A DataView lets you specify a criteria for
filtering and sorting a DataSet.

A DataSet is not a recordset. A DataView is more analogous to a
recordset.

DataSetCommand Objects
While the DataSet object provides a tool for in-memory data storage, you need
another tool to create and initialize the various tables. This tool is the
DataSetCommand object and represents a centralized console that hides the
details of working with connections and commands. The DataSetCommand

object allows for the retrieval and saving of data between a DataSet object and
the source data store. It is responsible for pulling out data from the physical
store and pushing it into data tables and relations. The DataSetCommand
object is also responsible for transmitting any update, insertion, or deletion to
the physical database. There are four command objects that you can use to
make any updates: UpdateCommand, InsertCommand, DeleteCommand,
and SelectCommand.
Note
6 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

The DataSetCommand object exists in two forms: SQLDataSetCommand
objects and ADODataSetCommand objects. The data source is Microsoft
®

SQL Server 7.0 (or later) for SQLDataSetCommand objects and any other
OLE DB provider for ADODataSetCommand objects.
Module 3: Using ADO.NET to Access Data 7

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

RecordSets vs. DataSets
!
DataSet
$
Multiple Tables
$
Includes Relationship
$

Navigate via Relationship
$
Disconnected
$
Transmit XML File
!
RecordSet
$
One Table
$
Based on Join
$
Move Row by Row
$
Connected or
Disconnected
$
COM Marshalling


In ADO, the in-memory representation of database data is the recordset. In
ADO.NET, it is the DataSet. The DataSet contains a collection of tables and
knowledge of relationships between those tables. Each table contains a
collection of columns. These objects represent the schema of the DataSet. Each
table can then have multiple rows, representing the data held by the DataSet.
These rows remember their original state along with their current state, so that
the DataSet tracks what kinds of changes have occurred. Additionally, the
DataSet provides persistence and de-persistence through XML.
There are important differences between recordsets and DataSets.
Number of Tables

An ADO recordset looks like a single table. If a recordset is to contain data
from multiple database tables, it must use a JOIN query, which assembles the
data from the various database tables into a single result table.
In contrast, an ADO.NET DataSet is a collection of one or more tables. The
tables within a data set are called data tables; specifically, they are DataTable
objects. .
Relationships
Typically a DataSet also contains relationships. A relationship within a
DataSet is analogous to a foreign-key relationship in a database. In ADO.NET,
a DataRelation represents the relationship.
Topic Objective
To highlight the differences
between DataSets and
RecordSets.
Lead-in
In ADO, you used
RecordSets
8 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Moving Through Data
In ADO.NET, the methods you use to read or modify data differ from the
programming methods you use in ADO in the following ways:
!
In ADO, you scan sequentially through the rows of the recordset.
!
In ADO.NET, you employ a navigation paradigm, moving from a row of
one data table to the corresponding row or rows of another data table by
following the relationship.


Disconnected Data
In ADO.NET, the DataSet provides disconnected access to database data. In
ADO, the recordset can provide disconnected access, but is typically used to
provide connected access.
Transmitting Data
To transmit an ADO disconnected recordset from one component to another,
you use COM marshalling. To transmit an ADO.NET data set, you simply
transmit an XML file.
Module 3: Using ADO.NET to Access Data 9

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Using Namespaces
!
Use the Import construct to declare namespaces
!
Namespaces Used with ADO.NET Include:
$
System.Data
$
System.Data.ADO
$
System.Data.SQL
$
System.Data.XML
$
System.Data.SQLTypes
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQL" %>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQL" %>


The .NET framework is an object-oriented system. When using specific parts of
the framework, you need to include references to the appropriate namespace in
your ASP.NET page.
When using ADO.NET from either Microsoft
®
Visual Basic
®
7.0 or Microsoft
®

Visual

C#, you must reference the System.Data namespace, as well as either
System.Data.ADO or System.Data.SQL namespace, depending on which data
source you choose to use. System.Data provides the code facilities, while
System.Data.ADO and System.Data.SQL are the namespaces for the two
managed providers.
In C# you use the keyword Using to import a namespace. In Visual Basic, you
declare namespaces at the top of an ASP.NET page, using the Import
construct.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQL" %>

The following table summarizes the list of available namespaces with
ADO.NET.
Namespace Contains


System.Data Base objects and types for ADO.NET
System.Data.ADO Managed OLEDB data store objects
System.Data.SQL SQL Server specific implementations of ADO.NET
objects
System.Data.XML XML objects
System.Data.SQLTypes SQL data types

Topic Objective
To describe the new
namespaces used with
ADO.NET.
Lead-in
In ASP.NET pages, you
have to specify the
namespace that you wish to
use. It is similar to using
references in a Visual Basic
program.
10 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Connecting to a Data Source
!
Using SQLConnection
!
Using ADOConnection
Dim strConn As String = _
"server=localhost; uid=sa;pwd=; database=northwind"

Dim conn As SQLConnection = New SQLConnection(strConn)
conn.Open()
Dim strConn As String = _
"server=localhost; uid=sa;pwd=; database=northwind"
Dim conn As SQLConnection = New SQLConnection(strConn)
conn.Open()
Dim strConn As String = "Provider= SQLOLEDB.1; " & _
"Data Source=localhost; uid=sa; pwd=; " & _
"InitialCatalog=northwind;"
Dim conn As ADOConnection = New ADOConnection(strConn)
conn.Open()
Dim strConn As String = "Provider= SQLOLEDB.1; " & _
"Data Source=localhost; uid=sa; pwd=; " & _
"InitialCatalog=northwind;"
Dim conn As ADOConnection = New ADOConnection(strConn)
conn.Open()


The Connection object defines how to connect to a specific data store. The
.NET framework provides two Connection objects: SQLConnection and
ADOConnection. The SQLConnection object defines how to connect to SQL
Server databases and the ADOConnection object allows you to establish a
connection to a database through an OLE DB provider.
Using SQLConnection
The following code illustrates how to create and open a connection to a SQL
Server database by using the SQLConnection object.
Dim strConn As String = _
"server=localhost;uid=sa;pwd=;database=northwind"
Dim conn As SQLConnection = New SQLConnection(strConn)


Using ADOConnection
For the ADO Managed Provider, the connection string format is quite similar to
the connection string format used in ADO.
The following code illustrates how to create and open a connection to a SQL
Server database by using ADOConnection.
Dim strConn As String = "Provider=SQLOLEDB.1; " & _
"Data Source=localhost; uid=sa; pwd=; " & _
"Initial Catalog=northwind;"
Dim conn As ADOConnection = New ADOConnection(strConn)


For the same code in ADO, the connection string would be
“Provider=SQLOLEDB; Data Source=(LOCAL); User ID=sa; Password=;
Initial Catalog=northwind”.

Topic Objective
To describe how to connect
to a data source by using
ADO.NET.
Lead-in
Connecting to a data source
is the first step in data
access.
Note
Module 3: Using ADO.NET to Access Data 11

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

We will be using SQLConnection objects for the examples in this module.
Implementation is slightly different for using ADOConnections. For more

information on using ADOConnections, see the .NET Framework SDK
documentation.

When connecting to a database through an ASP.NET page there are two
routes that you can take: use ADO or use the native SQL provider. The native
SQL provider is faster, but the catch is you must be using Microsoft SQL
Server as your database. If you are going to be using Access, Excel, a comma-
delimited file, or some other data source, you must use the ADO provider. You
can use the ADO provider just fine with SQL Server, however it is not as fast as
the native SQL provider.

Delivery Tip
Stress to students that all
examples in the module and
lab will be using
SQLConnection objects.
Note
12 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

#

Accessing Data With DataSets
!
Using DataSets to Read Data
!
Storing Multiple Tables in a DataSet
!
Using DataViews

!
Displaying Data in the DataGrid Control
!
Demonstration: Displaying Data in a DataGrid
!
Practice: Viewing a DataSet
!
Using Templates
!
Using the Repeater Control
!
Demonstration: Displaying Data in a Repeater Control


ADO.NET provides two ways of accessing data, using DataSets and
DataReaders.
In this section, you will learn how to access data by using DataSets. You will
also learn about using DataViews and displaying data in list-bound controls. At
the end of the section, you will learn how to customize a list-bound control by
using templates.
Topic Objective
To introduce the topics
included in the section.
Lead-in
After connecting to a
database, the next step is to
access data from it.
Module 3: Using ADO.NET to Access Data 13

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY


Using DataSets to Read Data
Dim cmdAuthors As SQLDataSetCommand
cmdAuthors = New SQLDataSetCommand _
("select * from Authors", conn)
Dim cmdAuthors As SQLDataSetCommand
cmdAuthors = New SQLDataSetCommand _
("select * from Authors", conn)
!
Create the Database Connection
!
Store the Query in a DataSetCommand
!
Create and Populate the DataSet
Dim ds As DataSet
ds = New DataSet()
cmdAuthors.FillDataSet(ds, "Authors")
Dim ds As DataSet
ds = New DataSet()
cmdAuthors.FillDataSet(ds, "Authors")


After you establish a connection to a database, you can access its data.
ADO.NET provides multiple ways of accessing data.
Using DataSets
The DataSet object is the centerpiece of ADO.NET. It represents a complete
set of data including multiple, related tables, and constraints.
While DataSets store data, you need DataSetCommand objects to create and
initialize the various tables. You also need the FillDataSet method to populate
a DataSet with the results from a query. The FillDataSet method takes two

parameters: a DataSet instance and a source table name. The DataSet instance
represents the DataSet to be filled, and the source table name identifies the table
inside the DataSet.
Let’s look at an example of using DataSets and DataSetCommands to retrieve
data from a database.
Example
The following code example illustrates how to create a SQLDataSetCommand
object that contains the query statement. The FillDataSet method then
populates the DataSet with the results from the query.
'Create a connection
Dim conn As SQLConnection = New SQLConnection _
("server=localhost;uid=sa;pwd=;database=pubs")
'Create the DataSetCommand
Dim cmdAuthors As SQLDataSetCommand = New SQLDataSetCommand _
("select * from Authors", conn)
'Create and populate the DataSet
Dim ds As DataSet()
ds= New DataSet()
cmdAuthors.FillDataSet(ds, "Authors")

Topic Objective
To describe how to retrieve
data from a database by
using DataSets.
Lead-in
Now that we can establish a
connection, we need to be
able to execute statements
against the database to
retrieve data.

14 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Storing Multiple Tables in a DataSet
!
Add the first table
!
Add the subsequent table(s)
command = New SQLDataSetCommand _
("select * from Authors", conn)
command.FillDataSet(ds, "Authors")
command = New SQLDataSetCommand _
("select * from Authors", conn)
command.FillDataSet(ds, "Authors")
command.SelectCommand = new SQLCommand _
("select * from Books", conn)
command.FillDataSet(ds, "Books")
command.SelectCommand = new SQLCommand _
("select * from Books", conn)
command.FillDataSet(ds, "Books")


A DataSet can contain multiple tables. In fact, you can simultaneously retrieve
and store multiple tables into a DataSet.
!
To retrieve and store multiple tables in a DataSet
1. Create and populate the first DataSet.
2. Reset the SelectCommand, InsertCommand, or DeleteCommand
property of the DataSetCommand object to a new Command object with a

new SQL statement.
cmd.SelectCommand = New SQLCommand("select * from Books", _
conn)

3. Call FillDataSet again.

Topic Objective
To explain how to retrieve
and store multiple tables in
a DataSet.
Lead-in
Unlike a disconnected
recordset, DataSets can
hold more than one table.
Module 3: Using ADO.NET to Access Data 15

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

The following code shows how you can add two tables from two different
queries, one for authors and the other for books, to the same DataSet.
Dim strConn As String
Dim conn As SQLConnection
Dim SQL As String
Dim command As SQLDataSetCommand
Dim ds As DataSet

'create connection to database
strConn = "server=localhost;uid=sa;pwd=;database=northwind"
conn = New SQLConnection(strConn)


'fill DataSet with first set of data
SQL = "Select * from Authors"
command = New SQLDataSetCommand (SQL, conn)
ds = New DataSet()
command.FillDataSet(ds, "Authors")

'fill DataSet with second set of data
SQL = "select * from Books"
command.SelectCommand = New SQLCommand(SQL, conn)
command.FillDataSet(ds, "Books")

16 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Using DataViews
!
DataViews can be customized to present a subset of
data from a DataTable
!
The DefaultView property returns the default DataView
for the table
!
Setting up a different view of a DataSet
Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dgAuthors.RowFilter = "state = 'CA'"
Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dgAuthors.RowFilter = "state = 'CA'"

Dim dv as DataView
dv = ds.Tables("Authors").DefaultView
Dim dv as DataView
dv = ds.Tables("Authors").DefaultView


To access the actual data held within a DataSet, you need to use a DataView.
DataViews can be customized to present a subset of data from the DataTable.
This capability allows you to have two controls bound to the same DataTable,
but showing different versions of the data. For example, one control may be
bound to a DataView showing all of the rows in the table, while a second may
be configured to display only the rows that have been deleted from the
DataTable.
Each DataTable in a DataSet has a DefaultView property, which returns the
default view for the table. You can access the default DataView on a DataSet
as follows:
Dim dv As DataView
dv = ds.Tables("Authors").DefaultView


The DataSet object contains a Tables collection. You reference the table
you are interested in by name.

You can also create a view of a subset of the data in a DataTable. For example,
you can set the RowFilter property on a DataView to retrieve only authors
from California.
Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dv.RowFilter = "state = 'CA'"


For more information on the properties of the DataView object, see the .NET
Framework SDK documentation.
Topic Objective
To explain the role of
DataViews in accessing
data from a database by
using DataSets.
Lead-in
To access data from a
DataSet, you need
DataViews.
Note
Module 3: Using ADO.NET to Access Data 17

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Displaying Data in the DataGrid Control
!
Create the control
!
Bind to a DataView
dgAuthors.DataSource=ds.Tables("Authors").DefaultView
dgAuthors.DataBind()
dgAuthors.DataSource=ds.Tables("Authors").DefaultView
dgAuthors.DataBind()
<asp:DataGrid id="dgAuthors" runat="server" />
<asp:DataGrid id="dgAuthors" runat="server" />


Displaying data from a data source is extremely simple and flexible in

ASP.NET. ASP.NET includes a set of controls that perform the function of
displaying data. The developers only need to bind these controls to a data
source.
To display data on the client, you can use any list-bound control, such as
DataGrid, DataList, or DataRepeater.
Using the DataGrid Control
The DataGrid control is designed to produce HTML output that resembles a
spreadsheet.
<asp:DataGrid id="dgAuthors" runat="server" />

To bind a DataSet to a DataGrid control, you first need to set the DataSource
property of the DataGrid to a DataView, either the DefaultView property of a
DataSet or a custom DataView object, and then call the DataBind method.
dgAuthors.DataSource = ds.Tables("Authors").DefaultView
dgAuthors.DataBind()


In the current version of ASP.NET, you have to bind to the
DefaultView of a DataSet. In the Beta 2 version of ASP.NET, you will be able
to bind directly to a DataSet. Therefore the above code will change to:
dgAuthors.DataSource =ds
dgAuthors.DataBind()

If you want to display a different view of data in the DataGrid control, create a
new DataView object from the DataSet and bind that to the control. For
example, the following code will display only those authors living in California.
Topic Objective
To describe how to display
data on the client in list-
bound controls.

Lead-in
After you connect to a data
source and retrieve data
from it, the next step is to
display data on the client.
For Your Information
In Beta2 of ASP.NET, you
will be able to bind a
DataGrid directly to a
DataSet if you want to
display all the information in
the DataSet.
Example using the
default view
Important
18 Module 3: Using ADO.NET to Access Data

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dv.RowFilter = "state = 'CA'"
dgAuthors.DataSource = dv
dgAuthors.DataBind()

The following illustration shows the default format of the DataGrid control.


Example using a custom
view

Module 3: Using ADO.NET to Access Data 19

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY

Demonstration: Displaying Data in a DataGrid


In this demonstration, you will see how to read data from a database into a
DataSet and then display it in a DataGrid control.

Topic Objective
To introduce the
demonstration.
Lead-in
In this demonstration, you
will see how to read data
from a database with
ADO.NET and display it in a
DataGrid control.
Delivery Tip
1. Open the file.
\DemoCode\Mod03\grid.asp
x.
2. Show the two DataGrid
controls. The first uses
some formatting attributes to
make it look nicer.
3. Show the Page_Load
event procedure that makes
a connection to the

database and creates a
DataSet.
4. The first DataGrid is
bound to the DefaultView.
5. The second DataGrid is
bound to a new DataView
that is a filtered version of
the data.
6. Open the page in
Microsoft
®
Internet
Explorer
®.

×