7.4. Binding Data to a Web Forms DataGrid


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


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>

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


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.


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


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

Get ADO.NET Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.