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

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

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