- •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
Session 24—Beating the CRUD out of the DataGrid Control |
249 |
The last piece of information we need to call our UpdateTitles function is the Title Id, which can be found by looking at the bound datakeys collection and passing the edited rows itemindex value:
sTitleId = titlegrid.datakeys.item(e.item.itemindex)
Now that we have the Title Id and the updated price, we can call our UpdateTitles function and pass these values. Finally, before we finish we will need to set the DataGrid control back to ReadOnly and rebind the updated data to the grid so that the cell is set to a read-only status.
titleGrid.EditItemIndex=-1 BindData()
The following code provides a listing of the UpdateTitles subroutine, which actually performs the database update of the price:
Sub UpdateTitles(price As Decimal, title_id As String)
Dim connection as New OleDBConnection(“provider=sqloledb;Data Source=localhost;Initial Catalog=pubs;User ID=sa;pwd=”)
Dim command as New OleDbCommand(“UPDATE titles SET [price]=? WHERE [title_id] =?”, connection)
Dim param0 as New OleDBParameter(“price”, OleDBType.Currency) param0.Value = price
command.Parameters.Add(param0)
Dim param1 as New OleDBParameter(“title_id”, OleDBType.VarChar) param1.Value = title_id
command.Parameters.Add(param1)
connection.Open()
command.ExecuteNonQuery()
connection.Close() End Sub
Deleting Data with the OnDeleteCommand Event
Unfortunately, the EditCommandColumn doesn’t provide an automated way to generate a Delete or Select hyperlink. However, you can use the ButtonColumn to implement a Delete method for the DataGrid control as shown in the following code:
<asp:ButtonColumn Text=”Delete” CommandName=”Delete”> </asp:ButtonColumn>
We attach a subroutine to execute when the hyperlink is selected as illustrated in Figure 24-2 with the following attribute of the DataGrid control:
OnDeleteCommand=”OnDelete”
The following code illustrates the subroutine that fires when the hyperlink is selected:
Sub OnDelete(sender As Object, E As DataGridCommandEventArgs)
Try
Dim sTitleId as String
250 |
Sunday Morning |
Dim sAuthorID as String sender.EditItemIndex=-1
sTitleId = titlegrid.datakeys.item(e.item.itemindex) sAuthorID = AuthorList.SelectedItem.Value DeleteTitles(sTitleId, sAuthorId)
BindData()
Message.Text=”Status: Delete Successful” Catch myException as Exception
Message.Text = (“Exception: “ + myException.ToString()) End Try
End Sub
When the OnDelete subroutine is executed, we first set the DataGrid control to ReadOnly to prevent any misplaced user interfaces once the selected row is deleted as illustrated in the following code segment.
sender.EditItemIndex=-1
Next, we obtain the Title Id and Author Id in the same way that we collected them in the update scenarios earlier. Once we have the Title Id and Author Id we can call the DeleteTitles subroutine to execute the actual delete as shown in the following example:
Sub DeleteTitles(title_id as String, au_id as String)
Dim connection as New OleDBConnection(“provider=sqloledb;Data Source=localhost;Initial Catalog=pubs;User ID=sa;pwd=”)
Dim command as New OleDbCommand(“DELETE FROM TitleAuthor WHERE [title_id]=? And [au_id]=?”, connection)
Dim param0 as New OleDBParameter(“title_id”, OleDBType.VarChar) param0.Value = title_id
command.Parameters.Add(param0)
Dim param1 as New OleDBParameter(“au_id”, OleDBType.VarChar) param1.Value = au_id
command.Parameters.Add(param1)
connection.Open()
command.ExecuteNonQuery()
connection.Close() End Sub
Finally, we call the BindData function to refresh the DataGrid control.
Sorting Columns with the DataGrid Control
Because the DataGrid control doesn’t perform the actual sorting of the data but instead handles the related events and methods, several steps must be taken in order to implement sorting on the DataGrid control.
The first step is to set up the following two attributes on the <ASP:DATAGRID>:
OnSortCommand=”OnSorted”
AllowSorting=”True”
The OnSortCommand is the event that will be called when a user initiates a sort event. The OnSorted subroutine builds the sorted DataView and rebinds the sorted information to
Session 24—Beating the CRUD out of the DataGrid Control |
251 |
the DataGrid control. The AllowSorting attribute will turn the column headers of all template columns or bound columns that have implemented a SortExpression attribute into a hyperlink that users can click to initiate the OnSortCommand. An example of how to add the attribute to a TemplateColumn can be seen below:
<asp:TemplateColumn HeaderText=”Unit Price” SortExpression=”price” >
The OnSorted subroutine handles all of the heavy lifting associated with the sorting activity. The OnSorted subroutine used in our example can be reviewed in Listing 24-3.
Listing 24-3 Example of implementing a sorting function for a DataGrid control
Sub OnSorted(source As Object , e As DataGridSortCommandEventArgs) Try
Dim sSortField as String
Dim TitlesDataView As DataView = GetTitles(authorlist.SelectedItem.Value)
Dim bSortAsc as Integer
sSortField = e.SortExpression.ToString() source.EditItemIndex=-1
if Session(“bsortAsc”) = Nothing Then Session(“bsortAsc”) = 1
Else
bSortAsc= Session(“bsortAsc”) End If
If bSortAsc = 1 Then Session(“bSortAsc”) = 0
TitlesDataView.Sort= sSortField & “ DESC” Message.Text =”Sort Descending on “ & sSortField
Elseif bSortAsc =0 Then Session(“bSortAsc”)= 1 TitlesDataView.Sort= sSortField & “ ASC”
Message.Text =”Sort Ascending on “ & sSortField Else
Message.Text=”bSortAsc fell through” End If
titleGrid.DataSource = TitlesDataView titlegrid.databind()
Catch myException as Exception
Message.Text = (“Exception: “ + myException.ToString()) End Try
End Sub
To handle the sorting of a column on the DataGrid control, you need to first establish a DataView object that can be used to sort the information. In the OnSorted function, you call the GetTitles function and pass the appropriate Author Id:
Dim TitlesDataView As DataView = GetTitles(authorlist.SelectedItem.Value)
Next, you need to know what field the user selected for sorting; we can get the field name through the SortExpression property:
sSortField = e.SortExpression.ToString()
252 |
Sunday Morning |
You also need to track whether the user desires the sort to be in ascending or descending order. In our example, we track this through the use of a session variable bSortAsc. When the value is equal to 1 then the sort is set for ascending, otherwise it is set for descending.
Once you know the field to sort on and the sorting direction, you can use the DataView to automatically sort the information using the Sort method of the DataView. You simply pass the name of the field to sort followed by the value ASC if you want the field sorted in ascending order or DESC if you want it sorted in descending order.
TitlesDataView.Sort= sSortField & “ ASC”
Finally, we simply bind the DataView to the grid as follows:
titleGrid.DataSource = TitlesDataView titlegrid.databind()
Figure 24-3 shows the resulting output of a user sorting the DataGrid control on the Unit Price field.
Figure 24-3 Output after sorting the Unit Price field
REVIEW
We have covered most of the major aspects of using the DataGrid control with ADO.NET and providing a user interface to support data updates, reads, and deletes. The examples provided for this session also demonstrate how to handle paging of data with the DataGrid control. You should explore these examples further to understand this technique.