Recipe 2.15. Navigating and Sorting Within a GridView


Problem

You want to use a GridView with sorting and paging.

Solution

Enable the sorting and paging functions of the GridView and add custom coding to display the sort order in the header of the current sort column. Figure 2-16 shows a typical GridView with sorting and paging implemented. Examples 2-39, 2-40 through 2-41 show the .aspx file and the code-behind files for an application that produces this output.

Figure 2-16. Combining sorting and paging in a GridView output


Discussion

Unlike the DataGrid, the GridView provides the ability to perform sorting and paging without having to write any custom code. But because the GridView does not provide any indication of the current sort column or order, you may want to write a small amount of custom code to accomplish this, as described in this recipe.

As a first step, the GridView, an excellent addition to the ASP.NET 2.0 controls, provides the ability to implement standard sorting and paging with little code. Sorting and paging are enabled by setting the AllowSorting and AllowPaging attributes to TRue.

 <asp:GridView  Runat="Server"  AllowPaging="true"  AllowSorting="true"  ShowHeader="true"

The ShowHeader attribute must be set to true to support sorting since the header provides the controls used to perform the sorting.

In addition, the HeaderText for each column that needs to support sorting cannot be set to an empty string. Otherwise, the control used to perform the sort operation for the column will not be rendered.


The Page_Load event handler in our application initializes the SqlDataSource and then sets the DataSourceID of our GridView to the ID of the SqlDataSource.

The GridView's built-in sorting and paging works only if the DataSourceID property of the GridView is set to the ID of the data source. If you use the DataSource property instead, you will have to implement all of the same event handlers that are required to perform sorting and paging with a DataGrid (see Recipe 2.11).


By default, the SortExpression property of the GridView is set to an empty string and the SortDirection property is set to Ascending. To set the sort column and sort to meet your needs, you will need to call the Sort method of the GridView passing the desired sort expression and order. This is required since the SortExpression and SortDirection properties are read-only and cannot be set directly. In our application, we set the initial sort column to the Title column and the sort order to Ascending.

 

If (Not Page.IsPostBack) Then 'perform the initial sort on the first column in ascending order gvBooks.Sort(gvBooks.Columns(0).SortExpression, _ SortDirection.Ascending) End If

if (!Page.IsPostBack) { // perform the initial sort on the first column in ascending order gvBooks.Sort(gvBooks.Columns[0].SortExpression, SortDirection.Ascending); }

Call the Sort method only if the page is initially being displayed. If the Sort method is called for each postback, the data will always be sorted using the defaults.


To mark the current sort column and order in the GridView' s header, custom code is required in the RowCreated event handler. Since the RowCreated event occurs for each row created in the GridView, you must first check to see if the row that has been created is the header.

 

If (e.Row.RowType = DataControlRowType.Header) Then … End If 'If (gvBooks.SortExpression.Equals(String.Empty))

if (e.Row.RowType == DataControlRowType.Header) { … } // if (e.Row.RowType == DataControlRowType.Header)

If the row that has been created is the header, you will need to loop through all of the columns in the GridView to determine which column matches the current sort expression. When the current sort column is determined, you need to check the sort direction and then add an HTML image to the controls in the header column to indicate the sort direction.

 

If (col.SortExpression.Equals(gvBooks.SortExpression)) Then 'this is the sort column so determine whether the ascending or 'descending image needs to be included image = New HtmlImage() image.Border = 0 If (gvBooks.SortDirection = SortDirection.Ascending) Then image.Src = "images/sort_ascending.gif" Else image.Src = "images/sort_descending.gif" End If 'add the image to the column header e.Row.Cells(index).Controls.Add(image)

if (col.SortExpression.Equals(gvBooks.SortExpression)) { // this is the sort column so determine whether the ascending or // descending image needs to be included image = new HtmlImage(); image.Border = 0; if (gvBooks.SortDirection == SortDirection.Ascending) { image.Src = "images/sort_ascending.gif"; } else { image.Src = "images/sort_descending.gif"; } // add the image to the column header e.Row.Cells[index].Controls.Add(image); } // if (col.SortExpression.Equals(gvBooks.SortExpression))

See Also

Recipes 2.11 and 2.15

Example 2-39. Combining sorting and paging in a GridView (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH02GridViewWithSortingAndPagingVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02GridViewWithSortingAndPagingVB" Title="GridView With Sorting and Paging" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > GridView With Sorting and Paging (VB) </div> <asp:SqlDataSource  runat="server" /> <asp:GridView  Runat="Server" AllowPaging="true" AllowSorting="true" ShowHeader="true" AutoGenerateColumns="false" BorderColor="#000080" BorderStyle="Solid" BorderWidth="2px" Caption="" HorizontalAlign="Center" Width="90%" PageSize="5" PagerSettings-Mode="Numeric" PagerSettings-PageButtonCount="5" PagerSettings-Position="Bottom" PagerStyle-HorizontalAlign="Center" PagerSettings-NextPageText="Next" PagerSettings-PreviousPageText="Prev" PagerStyle-Css OnRowCreated="gvBooks_RowCreated" > <HeaderStyle HorizontalAlign="Center" Css /> <RowStyle css /> <AlternatingRowStyle css /> <Columns> <asp:BoundField DataField="Title" HeaderText="Title " SortExpression="Title" /> <asp:BoundField DataField="ISBN" HeaderText="ISBN " ItemStyle-HorizontalAlign="Center" SortExpression="ISBN" /> <asp:BoundField DataField="Publisher" HeaderText="Publisher " ItemStyle-HorizontalAlign="Center" SortExpression="Publisher" /> </Columns> </asp:GridView> </asp:Content> 

Example 2-40. Combining sorting and paging in a GridView (.vb)

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH02GridViewWithSortingAndPagingVB.aspx ''' </summary> Partial Class CH02GridViewWithSortingAndPagingVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load 'configure the data source to get the data from the database 'NOTE: This code must be executed anytime the page is rendered ' including postbacks dSource.ConnectionString = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dSource.DataSourceMode = SqlDataSourceMode.DataSet dSource.ProviderName = "System.Data.OleDb" dSource.SelectCommand = "SELECT Title, ISBN, Publisher " & _ "FROM Book " &_  "ORDER BY Title" 'set the data source ID for the GridView 'NOTE: The DataSourceID must be used instead of the DataSource if the ' automatic sorting/paging in GridView are to be used. gvBooks.DataSourceID = dSource.ID If (Not Page.IsPostBack) Then 'perform the initial sort on the first column in ascending order gvBooks.Sort(gvBooks.Columns(0).SortExpression, _ SortDirection.Ascending) End If End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the GridView's row created ''' event. It is responsible for setting the icon in the header row to ''' indicate the current sort column and sort order ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub gvBooks_RowCreated(ByVal sender As Object, _ ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Dim index As Integer Dim col As DataControlField = Nothing Dim image As HtmlImage = Nothing If (e.Row.RowType = DataControlRowType.Header) Then 'loop through the columns in the gridview updating the header to 'mark which column is the sort column and the sort order For index = 0 To gvBooks.Columns.Count - 1 col = gvBooks.Columns(index) 'check to see if this is the sort column If (col.SortExpression.Equals(gvBooks.SortExpression)) Then 'this is the sort column so determine whether the ascending or 'descending image needs to be included image = New HtmlImage() image.Border = 0 If (gvBooks.SortDirection = SortDirection.Ascending) Then image.Src = "images/sort_ascending.gif" Else image.Src = "images/sort_descending.gif" End If 'add the image to the column header e.Row.Cells(index).Controls.Add(image) End If 'If (col.SortExpression = sortExpression) Next index End If 'If (gvBooks.SortExpression.Equals(String.Empty)) End Sub 'gvBooks_RowCreated End Class 'CH02GridViewWithSortingAndPagingVB End Namespace 

Example 2-41. Combining sorting and paging in a GridView (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH02GridViewWithSortingAndPagingCS.aspx /// </summary> public partial class CH02GridViewWithSortingAndPagingCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. It /// is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> private void Page_Load(Object sender, System.EventArgs e) { // configure the data source to get the data from the database // NOTE: This code must be executed anytime the page is rendered // including postbacks dSource.ConnectionString = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dSource.DataSourceMode = SqlDataSourceMode.DataSet; dSource.ProviderName = "System.Data.OleDb"; dSource.SelectCommand = "SELECT Title, ISBN, Publisher " + "FROM Book " + "ORDER BY Title"; // set the data source ID for the GridView // NOTE: The DataSourceID must be used instead of the DataSource if the // automatic sorting/paging in GridView are to be used. gvBooks.DataSourceID = dSource.ID; if (!Page.IsPostBack) { // perform the initial sort on the first column in ascending order gvBooks.Sort(gvBooks.Columns[0].SortExpression, SortDirection.Ascending); } } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the GridView's row created /// event. It is responsible for setting the icon in the header row to /// indicate the current sort column and sort order /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void gvBooks_RowCreated(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { DataControlField col = null; HtmlImage image = null; if (e.Row.RowType == DataControlRowType.Header) { // loop through the columns in the gridview updating the header to // mark which column is the sort column and the sort order for (int index = 0; index < gvBooks.Columns.Count; index++) { col = gvBooks.Columns[index]; // check to see if this is the sort column if (col.SortExpression.Equals(gvBooks.SortExpression)) { // this is the sort column so determine whether the ascending or // descending image needs to be included image = new HtmlImage(); image.Border = 0; if (gvBooks.SortDirection == SortDirection.Ascending) { image.Src = "images/sort_ascending.gif"; } else { image.Src = "images/sort_descending.gif"; } // add the image to the column header e.Row.Cells[index].Controls.Add(image); } // if (col.SortExpression.Equals(gvBooks.SortExpression)) } // for index } // if (e.Row.RowType == DataControlRowType.Header) } //gvBooks_RowCreated } // CH02GridViewWithSortingAndPagingCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net