O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

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

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

Combining sorting and paging in a GridView 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 ID="gvBooks" Runat="Server"
					 AllowPaging="true"
					 AllowSorting="true"
					 ShowHeader="true"

Tip

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

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