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.LoadCalls the
CreateDataSource( )method and binds data to the Web FormsDataGrid, if the page is being loaded for the first time.CreateDataSource( )This method fills a
DataTablewith the Orders table from the Northwind sample database and stores theDataTableto aSessionvariable to cache the data source for theDataGrid.DataGrid.PageIndexChangedGets the cached data from the
Sessionvariable, updates theCurrentPageIndexof theDataGrid, and binds the data to the grid.DataGrid.SortCommandGets the cached data from the
Sessionvariable, sets the sort order of the defaultDataViewfor the data, and binds thatDataViewto 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access