1. Trang chủ
  2. » Công Nghệ Thông Tin

Module 3: Using ADO.NET to Access Data

56 461 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Using ADO.NET to Access Data
Trường học Microsoft Corporation
Chuyên ngành Computer Science / Information Technology
Thể loại Lecture notes
Năm xuất bản 2000
Định dạng
Số trang 56
Dung lượng 1,02 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Contents Overview 1 Connecting to a Data Source 10 Accessing Data With DataSets 12 Accessing Data with DataReaders 37 Lab 3: Using ADO.NET to Access Data 49 Review 50 Module 3: Usi

Trang 1

Contents

Overview 1

Connecting to a Data Source 10

Accessing Data With DataSets 12

Accessing Data with DataReaders 37

Lab 3: Using ADO.NET to Access Data 49

Review 50

Module 3: Using ADO.NET to Access Data

Trang 2

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

Trang 3

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

Trang 4

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

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

Trang 5

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

Trang 7

Overview

! 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

In this module, you will learn

about the data binding

features in ASP.NET

Trang 8

# Overview of ADO.NET

! Animation: Using ADO.NET to Access Data

! RecordSets vs DataSets

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

Trang 9

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

Trang 10

The ADO.NET Object Model

DataSetCommand

Connection Database

Command

.ASPX Page

List-Bound Control

List-Bound Control

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

Trang 11

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

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

Trang 12

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

Trang 13

$ 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

Trang 14

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

Trang 15

Using Namespaces

! Use the Import construct to declare namespaces

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

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

Trang 16

Connecting to a Data Source

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=; " & _

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

Trang 17

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

Trang 18

# 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

To introduce the topics

included in the section

Lead-in

After connecting to a

database, the next step is to

access data from it

Trang 19

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

Trang 20

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)

! 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

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

Trang 21

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")

Trang 22

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

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

To access data from a

DataSet, you need

DataViews

Note

Trang 23

Displaying Data in the DataGrid Control

! Create the control

! Bind to a DataView

dgAuthors.DataSource=ds.Tables("Authors").DefaultViewdgAuthors.DataBind()

dgAuthors.DataSource=ds.Tables("Authors").DefaultViewdgAuthors.DataBind()

<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

Trang 24

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

Trang 25

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

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®.

Trang 26

Practice: Viewing a DataSet

In this practice, you will connect to the conference database, retrieve a DataSet,

and display the data in a DataGrid control

! Create a new page

1 Open the conference project that you have been working with

2 Create a new ASPX page

3 Import the System.Data and System.Data.SQL namespaces by typing the following code:

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

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

4 Add the beginning and ending HTML and BODY tags

5 In the BODY section, create a DataGrid control:

<ASP:DataGrid id="dgSessions" runat="server" />

6 Save the page as DataSet.aspx

! Create the DataSet

1 Create a SCRIPT section to run on the server

2 Create a Page_Load event procedure

3 Declare the following variables:

Dim ds As DataSet Dim conn As SQLConnection Dim cmdSessions As SQLDataSetCommand

Topic Objective

To introduce the practice

Lead-in

In this practice, you will

connect to the conference

database, retrieve a

DataSet, and display the

data in a DataGrid control

Trang 27

4 Create a new database connection:

conn = New SQLConnection _ ("server=localhost;uid=sa;pwd=;database=conf")

5 Create a new SQLDataSetCommand to hold the SQL query:

cmdSessions = New SQLDataSetCommand _ ("select * from sessions where duration='2'", conn)

6 Create a DataSet:

ds = new DataSet() cmdSessions.FillDataSet(ds, "Sessions")

7 Bind the DataSet to the DataGrid:

dgSessions.DataSource = ds.Tables("Sessions").DefaultView dgSessions.DataBind()

! To save and test the page

1 Save your changes

2 View the page in Internet Explorer

3 Experiment with some of the properties of the DataGrid control to change

Font-Name="Verdana"

Font-Size="8pt"

HeaderStyle-BackColor="#aaaadd"

Trang 28

AlternatingItem Template

ItemTemplate

Most ASP.NET controls have a standard look, but these might not be the looks that the user requires ASP.NET allows users to customize the look of some controls by using templates When a control supports a template, you add the ASP.NET template elements, and then within the template, you insert the elements and controls that you want to be displayed

List-bound controls support five types of templates The Repeater and

DataList controls can use these templates directly The DataGrid control can

only use these templates if they are bound to a column

Template Use

HeaderTemplate Elements to render once before any data-bound rows

have been rendered A typical use is to begin a container element such as a table

ItemTemplate Elements that are rendered once for each row in the data

source To display data in the ItemTemplate, declare one

or more Web controls and set their data-binding

expressions to evaluate to a field in the Repeater control's (that is, the container control's) DataSource:

First Name: <asp:Label runat="server"

Text="<%# Container.DataItem.FirstName %>" /> AlternatingItemTemplate Elements that are rendered for every other row in the

Repeater control

SeparatorTemplate Elements to render between each row, typically line

breaks (<BR> tags), lines (<HR> tags), and so on FooterTemplate Elements to render once when all data-bound rows have

been rendered A typical use is to close an element

opened in the HeaderTemplate item (with a tag such as

</TABLE>)

Topic Objective

To explain about the five

templates used by the

Repeater and DataList

controls

Lead-in

In ASP.NET, you can

customize the way

list-bound controls display data

Ngày đăng: 27/10/2013, 07:15

TỪ KHÓA LIÊN QUAN