- •Preface
- •Who Should Read This Book
- •Organization and Presentation
- •Contacting the Authors
- •Acknowledgments
- •Contents
- •Introduction
- •Why Microsoft .NET?
- •The Microsoft .NET Architecture
- •Internet Standards
- •The Evolution of ASP
- •The Benefits of ASP.NET
- •What Is .NET?
- •.NET Experiences
- •.NET Clients
- •.NET Services
- •.NET Servers
- •Review
- •Quiz Yourself
- •Installation Requirements
- •Installing ASP.NET and ADO.NET
- •Installing the .NET Framework SDK
- •Testing Your Installation
- •Support for .NET
- •Review
- •Quiz Yourself
- •Designing a Database
- •Normalization of Data
- •Security Considerations
- •Review
- •Quiz Yourself
- •Creating a Database
- •Creating SQL Server Tables
- •Creating a View
- •Creating a Stored Procedure
- •Creating a Trigger
- •Review
- •Quiz Yourself
- •INSERT Statements
- •DELETE Statements
- •UPDATE Statements
- •SELECT Statements
- •Review
- •Quiz Yourself
- •The XML Design Specs
- •The Structure of XML Documents
- •XML Syntax
- •XML and the .NET Framework
- •Review
- •Quiz Yourself
- •ASP.NET Events
- •Page Directives
- •Namespaces
- •Choosing a Language
- •Review
- •Quiz Yourself
- •Introducing HTML Controls
- •Using HTML controls
- •How HTML controls work
- •Intrinsic HTML controls
- •HTML Control Events
- •The Page_OnLoad event
- •Custom event handlers
- •Review
- •Quiz Yourself
- •Intrinsic Controls
- •Using intrinsic controls
- •Handling intrinsic Web control events
- •List Controls
- •Rich Controls
- •Review
- •Quiz Yourself
- •Creating a User Control
- •Adding User Control Properties
- •Writing Custom Control Methods
- •Implementing User Control Events
- •Review
- •Quiz Yourself
- •Common Aspects of Validation Controls
- •Display property
- •Type Property
- •Operator Property
- •Using Validation Controls
- •RequiredFieldValidator
- •RegularExpressionValidator
- •CompareValidator
- •RangeValidator
- •CustomValidator
- •ValidationSummaryx
- •Review
- •Quiz Yourself
- •Maintaining State Out of Process for Scalability
- •No More Cookies but Plenty of Milk!
- •Out of Process State Management
- •Review
- •Quiz Yourself
- •Introducing the Key Security Mechanisms
- •Web.config and Security
- •Special identities
- •Using request types to limit access
- •New Tricks for Forms-based Authentication
- •Using the Passport Authentication Provider
- •Review
- •Quiz Yourself
- •ASP.NET Updates to the ASP Response Model
- •Caching with ASP.NET
- •Page Output Caching
- •Absolute cache expiration
- •Sliding cache expiration
- •Fragment Caching
- •Page Data Caching
- •Expiration
- •File and Key Dependency and Scavenging
- •Review
- •Quiz Yourself
- •A Brief History of Microsoft Data Access
- •Differences between ADO and ADO.NET
- •Transmission formats
- •Connected versus disconnected datasets
- •COM marshaling versus text-based data transmission
- •Variant versus strongly typed data
- •Data schema
- •ADO.NET Managed Provider Versus SQL Managed Provider
- •Review
- •Quiz Yourself
- •Review
- •Quiz Yourself
- •Creating a Connection
- •Opening a Connection
- •Using Transactions
- •Review
- •Quiz Yourself
- •Building a Command
- •Connection property
- •CommandText property
- •CommandType property
- •CommandTimeout property
- •Appending parameters
- •Executing a Command
- •ExecuteNonQuery method
- •Prepare method
- •ExecuteReader method
- •Review
- •Quiz Yourself
- •Introducing DataReaders
- •Using DataReader Properties
- •Item property
- •FieldCount property
- •IsClosed property
- •RecordsAffected property
- •Using DataReader Methods
- •Read method
- •GetValue method
- •Get[Data Type] methods
- •GetOrdinal method
- •GetName method
- •Close method
- •Review
- •Quiz Yourself
- •Constructing a DataAdapter Object
- •SelectCommand property
- •UpdateCommand, DeleteCommand, and InsertCommand properties
- •Fill method
- •Update method
- •Dispose method
- •Using DataSet Objects
- •DataSetName property
- •CaseSensitive property
- •Review
- •Quiz Yourself
- •Constructing a DataSet
- •Tables property
- •TablesCollection Object
- •Count property
- •Item property
- •Contains method
- •CanRemove method
- •Remove method
- •Add method
- •DataTable Objects
- •CaseSensitive property
- •ChildRelations property
- •Columns property
- •Constraints property
- •DataSet property
- •DefaultView property
- •ParentRelations property
- •PrimaryKey property
- •Rows property
- •Dispose method
- •NewRow method
- •Review
- •Quiz Yourself
- •What Is Data Binding?
- •Binding to Arrays and Extended Object Types
- •Binding to Database Data
- •Binding to XML
- •TreeView Control
- •Implement the TreeView server control
- •Review
- •Quiz Yourself
- •DataGrid Control Basics
- •Binding a set of data to a DataGrid control
- •Formatting the output of a DataGrid control
- •Master/Detail Relationships with the DataGrid Control
- •Populating the Master control
- •Filtering the detail listing
- •Review
- •QUIZ YOURSELF
- •Updating Your Data
- •Handling the OnEditCommand Event
- •Handling the OnCancelCommand Event
- •Handling the OnUpdateCommand Event
- •Checking that the user input has been validated
- •Executing the update process
- •Deleting Data with the OnDeleteCommand Event
- •Sorting Columns with the DataGrid Control
- •Review
- •Quiz Yourself
- •What Is Data Shaping?
- •Why Shape Your Data?
- •DataSet Object
- •Shaping Data with the Relations Method
- •Review
- •Quiz Yourself
- •OLEDBError Object Description
- •OLEDBError Object Properties
- •OLEDBError Object Methods
- •OLEDBException Properties
- •Writing Errors to the Event Log
- •Review
- •Quiz Yourself
- •Introducing SOAP
- •Accessing Remote Data with SOAP
- •SOAP Discovery (DISCO)
- •Web Service Description Language (WSDL)
- •Using SOAP with ASP.NET
- •Review
- •Quiz Yourself
- •Developing a Web Service
- •Consuming a Web Service
- •Review
- •Quiz Yourself
- •ASP and ASP.NET Compatibility
- •Scripting language limitations
- •Rendering HTML page elements
- •Using script blocks
- •Syntax differences and language modifications
- •Running ASP Pages under Microsoft.NET
- •Using VB6 Components with ASP.NET
- •Review
- •Quiz Yourself
- •Preparing a Migration Path
- •ADO and ADO.NET Compatibility
- •Running ADO under ASP.NET
- •Early Binding ADO COM Objects in ASP.NET
- •Review
- •Quiz Yourself
- •Answers to Part Reviews
- •Friday Evening Review Answers
- •Saturday Morning Review Answers
- •Saturday Afternoon Review Answers
- •Saturday Evening Review Answers
- •Sunday Morning Review Answers
- •Sunday Afternoon Review Answers
- •What’s on the CD-ROM
- •System Requirements
- •Using the CD with Windows
- •What’s on the CD
- •The Software Directory
- •Troubleshooting
- •ADO.NET Class Descriptions
- •Coding Differences in ASP and ASP.NET
- •Retrieving a Table from a Database
- •Displaying a Table from a Database
- •Variable Declarations
- •Statements
- •Comments
- •Indexed Property Access
- •Using Arrays
- •Initializing Variables
- •If Statements
- •Case Statements
- •For Loops
- •While Loops
- •String Concatenation
- •Error Handling
- •Conversion of Variable Types
- •Index
S E S S I O N
23
Using the DataGrid Control with Bound Data
Session Checklist
Binding controls to one another
Implementing master-detail relationships
Using DataBound columns with the DataGrid control
This session assumes you have SQL Server installed and have access to the
Pubs database.
Note
In this session we cover the basics of the DataGrid control. We start out by describing how to bind datasets to the DataGrid control, including how to format the output, and how to handle master/detail relationships. After completing this session, you should be
able to understand how the DataGrid control can be used to eliminate much of the common scripting you did in ASP to handle the display of data in tables.
DataGrid Control Basics
ASP developers commonly face the problem of how to display a set of data in a table format. In ASP, you would typically open a RecordSet object and then use Response.Write to display the results in a dynamically generated table. In ASP.NET this task can be greatly simplified through the use of the DataGrid control.
Binding a set of data to a DataGrid control
In Listing 23-1, we have implemented a DataGrid by simply using the code:
<asp:datagrid id=”datagrid” runat=”server” />
234 |
Sunday Morning |
Next, we created a function BindData()that opens a connection to the Pubs database, selects all the records in the titles table, and then fills a DataSet object with the results. Finally, we use the datagrid.databind() method to execute the binding. This binds the dataset to the DataGrid control. The DataGrid control handles all of the effort associated with formatting the results into a table and displaying the resulting output.
Listing 23-1 Binding a Dataset to a DataGrid control
<%@ Import Namespace=”System.Data.OleDb” %> <%@ Import Namespace=”system.data” %>
<%@ Page Language=”VB” Debug=”False” Trace=”False”%> <HTML>
<SCRIPT LANGUAGE=”vb” RUNAT=”server”> DIM oConn as OleDbConnection
DIM oCmd as OleDbDataAdapter DIM oDS as new dataset
public sub page_load(sender as object,e as eventargs) if page.ispostback=false then
BindData() end if
end sub
Function BindData()
oConn=new OleDbConnection(“provider=sqloledb;Data Source=(local);Initial
Catalog=pubs;User ID=sa;pwd=;”)
oCmd=new OleDbDataAdapter(“select * from titles”,oConn)
oCmd.Fill(oDS,”titles”)
datagrid.datasource=oDS.tables(“titles”).defaultview
datagrid.databind()
End Function
</SCRIPT>
<BODY>
<FORM ID=”form1” RUNAT=”server”> <ASP:DATAGRID
ID=”datagrid”
RUNAT=”server”
AUTOGENERATECOLUMNS=”True”
DATAKEYFIELD=”title_id”> </ASP:DATAGRID>
</FORM>
</BODY>
</HTML>
The AutoGenerateColumns property is what automatically generates the columns for the resulting dataset. The DataKeyField property specifies what data field should be used as a primary key for the table. This will be important later when we discuss editing and updating data with the DataGrid control. In this scenario, we did not have much control over which columns were displayed or how the output of the columns was formatted, it is clear that a lot of custom code can be eliminated through the use of the DataGrid control. In the next section we show how to overcome these issues.
Session 23—Using the DataGrid Control with Bound Data |
235 |
Formatting the output of a DataGrid control
In the previous section, we let the DataGrid control handle all of the output properties by setting the AutoGenerateColumns attribute to True. In Listing 23-2, we have set this attribute to False and have instead used the Columns property combined with the ASP.NET BoundColumn control to select what fields are displayed and how they are formatted.
Listing 23-2 Using the BoundColumn control and DataFormatString with the DataGrid control
<ASP:DATAGRID ID=”datagrid” RUNAT=”server” AUTOGENERATECOLUMNS=”False” DATAKEYFIELD=”title_id”>
<COLUMNS>
<ASP:BOUNDCOLUMN HEADERTEXT=”YTD Sales” DATAFIELD=”ytd_sales” READONLY=”true” DATAFORMATSTRING=”{0:C}”>
</ASP:BOUNDCOLUMN>
</COLUMNS>
<ALTERNATINGITEMSTYLE BACKCOLOR=”Gainsboro” /> <FOOTERSTYLE FORECOLOR=”White” BACKCOLOR=”Silver” /> <ITEMSTYLE BACKCOLOR=”White” />
<HEADERSTYLE FONT-BOLD=”True” FORECOLOR=”White” BACKCOLOR=”Navy” /> </ASP:DATAGRID>
The DataField property determines what field in the dataset is displayed in the resulting output. In this case, we will display the ytd_sales field. Additionally, we have specified a specific formatting style for this data by using the DataFormatString property. The value for this property, {0:c}, will format the resulting output in the currency of the end user’s locale.
The data format string consists of two parts separated by a colon in the form of {X:Yxx}, where X specifies the parameter number in a zero-based list of parameters. This value can only be 0 because there is only one value in each cell. Y specifies the format to display the value as shown in Table 23-1.
Table 23-1 Formatting Styles Applied by the DataFormatString property
Format Character |
Description |
C |
Displays numeric values in currency format. |
|
|
D |
Displays numeric values in decimal format. |
|
|
E |
Displays numeric values in scientific (exponential) format. |
|
|
F |
Displays numeric values in fixed format. |
|
|
G |
Displays numeric values in general format. |
|
|
N |
Displays numeric values in number format. |
|
|
X |
Displays numeric values in hexadecimal format. |
|
|