O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.4. Binding Data to a Web Forms DataGrid

Problem

You want to bind the result set from a query to a DataGrid control.

Solution

Set the advanced properties of the DataGrid as demonstrated in the code for the Web Forms page as shown in Example 7-7.

Example 7-7. File: ADOCookbookCS0704.aspx

<asp:DataGrid id="dataGrid"
    style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 56px"
    runat="server" AllowPaging="True" AllowSorting="True">
    <AlternatingItemStyle BackColor="#FFFF99"></AlternatingItemStyle>
</asp:DataGrid>

The code-behind file contains three event handlers and one method:

Page.Load

Calls the CreateDataSource( ) method and binds data to the Web Forms DataGrid, if the page is being loaded for the first time.

CreateDataSource( )

This method fills a DataTable with the Orders table from the Northwind sample database and stores the DataTable to a Session variable to cache the data source for the DataGrid.

DataGrid.PageIndexChanged

Gets the cached data from the Session variable, updates the CurrentPageIndex of the DataGrid, and binds the data to the grid.

DataGrid.SortCommand

Gets the cached data from the Session variable, sets the sort order of the default DataView for the data, and binds that DataView to the grid.

The C# code for the code-behind is shown in Example 7-8.

Example 7-8. File: ADOCookbookCS0704.aspx.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; private void Page_Load(object sender, System.EventArgs ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required