Configuring the GridView and DetailsView controls
Paging and Sorting Data from a SqlDataSource
Paging and sorting data in a GridView that comes from a SqlDataSource is a breeze with ASP.NET 2.0. As in the demos before, start by adding a SqlDataSource that accesses the desired data. Next, add a GridView. The GridView's Smart Tag contains two checkboxes: Enable Paging and Enable Sorting. To turn on sorting and/or paging, simply check the appropriate checkboxes (see Figure 21). It's that simple!
Note The SqlDataSource has a DataSourceMode property that you can set to specify if the SqlDataSource returns a DataReader or DataSet, with DataSet being the default. When creating a pageable GridView you must return a DataSet. The GridView's sorting capabilities can only be utilized with either a DataSet or a DataReader, but when sorting by returning a DataReader you must retrieve your data from a stored procedure. Furthermore, this stored procedure must accept a parameter indicating the sort expression; specify the name of this input parameter through the SqlDataSource's SortParameterName property.
The ASP.NET page's declarative syntax can be seen below. As you can see, no source code is needed to create a pageable, bi-directional sortable GridView.
<%@ Page Language="C#" %>
Figures 22, 23, and 24 show the pageable, bi-directional sortable GridView in action. Figure 22 shows page 1 of the data, ordered by Product Name in ascending order. Figure 23 shows page 1, ordered by the Product Name in descending order. Figure 24 shows page 4, ordered by the Unit Price in ascending order.
Notice that the Quantity Per Unit column stands out from the other columns in that it does not have a hyperlink in its header. This means that the data cannot be sorted by Quantity Per Unit. You can specify if a column should be sortable or not by its SortExpression property. Refer back to the ASP.NET page's declarative syntax and you'll notice that the last BoundField (the Quantity Per Unit column) lacks a SortExpression attribute, while it's present for all other BoundFields.
At the bottom of the GridView you'll find text that informs the end user what page of data they're currently viewing along with how many total pages of data exist. The GridView exposes a zero-based PageIndex property that specified the current page of data being viewed along with a PageCount property that indicates how many total pages of data are available. To display this information, simply output the necessary markup using <%=...%> delimiters to emit the server-side property values.
You are viewing page <%=productsGridView.PageIndex + 1%> of <%=productsGridView.PageCount%>