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


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 e)
 dataGrid.DataSource = CreateDataSource( );
 dataGrid.DataKeyField = "OrderId";
 dataGrid.DataBind( );

private DataTable CreateDataSource( )
 DataTable dt = new DataTable( );

 // Create a DataAdapter and fill the Orders table with it.
 SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders",

 // Store data in session variable to store data between
 // posts to server.
 Session["DataSource"] = dt;

 return dt;

private void dataGrid_PageIndexChanged(object source,
 System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
 // Get the data from the session variable.
 DataView dv = ((DataTable)Session["DataSource"]).DefaultView;

 // Update the current page for the data grid.
 dataGrid.CurrentPageIndex = e.NewPageIndex;

 // Bind the data view to the data grid.
 dataGrid.DataSource = dv;
 dataGrid.DataBind( );

private void dataGrid_SortCommand(object source,
 System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
 // Get the data from the session variable.
 DataView dv = ((DataTable)Session["DataSource"]).DefaultView;

 // Set the sort of the data view.
 dv.Sort = e.SortExpression;

 // Bind the data view to the data grid.
 dataGrid.DataSource = dv;
 dataGrid.DataBind( ); 


The DataGrid Web Form control retrieves tabular information from a data source and renders it in a web page. The control supports functionality for selecting, editing, deleting, sorting, and navigating the data.

The DataGrid must be bound to a data source such as a DataReader , DataSet , DataTable , or DataView . Any class that implements the IEnumerable interface can be bound. The easiest way to create a DataGrid control is to drag the DataList control onto the web page design surface.

The DataGrid control uses templates to display items, control layout, and provide functional capabilities similar to the DataList as described in Recipe 7.3. The differences are:

  • Item templates are created for columns in the grid rather for the entire grid.
  • A DataGrid column does not have an AlternatingItemTemplate , or a SelectedItemTemplate , or a SeparatorItemTemplate .

To specify columns for and format the DataGrid , right-click on the DataList control on the design surface and select Property Builder . The DataGrid can also be customized by editing the HTML directly.

A variety of DataGrid columns can be specified, but by default, columns are automatically generated based on the fields in the data source. The DataGrid supports the column types described in Table 7-5.

Table 7-5. DataGrid column types

Column type



Specify the data source field to display as text.


A command button in the grid that can invoke custom logic when clicked.


A button that supports in-place editing. These buttons raise events specific to in-place editing described in Table 7-6.


Displays the contents as a hyperlink.


A custom layout based on a combination of HTML and Web Server controls in a specified template.

Among the events that the DataGrid supports are those designed to help implement common data editing and manipulation functionality. These events are described in Table 7-6.

Table 7-6. Common DataGrid events for editing and navigation



CancelCommand( )

Raised when the in-place editing Cancel button is clicked for an item in the control.

DeleteCommand( )

Raised when the in-place editing Delete button is clicked for an item in the control.

EditCommand( )

Raised when the in-place editing Edit button is clicked for an item in the control.

ItemCommand( )

Raised when a button other than an in-place editing button is clicked.

PageIndexChanged( )

Raised when one of the page selection elements is clicked. The AllowPaging property of the control must be set to true.

SelectedIndexChanged( )

Raised when a different item is selected in the control between posts to the server.

SortCommand( )

Raised when a column header is selected for sorting.

UpdateCommand( )

Raised when the in-place editing Update button is clicked for an item in the control.

The DataGrid does not inherently support editing, paging, sorting, or updating functionality. Instead, it exposes the events listed in Table 7-6, allowing the functionality to be added using event handling code.

After the properties appropriate to the control are set, call the DataBind( ) method of the control or of the page to bind the data source to the server control.

Connecting to Data

Retrieving and Managing Data

Searching and Analyzing Data

Adding and Modifying Data

Copying and Transferring Data

Maintaining Database Integrity

Binding Data to .NET User Interfaces

Working with XML

Optimizing .NET Data Access

Enumerating and Maintaining Database Objects

Appendix A. Converting from C# to VB Syntax

show all menu

ADO. NET Cookbook
ADO.NET 3.5 Cookbook (Cookbooks (OReilly))
ISBN: 0596101406
EAN: 2147483647
Year: 2002
Pages: 222
Authors: Bill Hamilton
Similar book on Amazon © 2008-2017.
If you may any questions please contact us: