2.10. Sorting Data in Ascending/Descending Order Within a DataGrid
Problem
You are displaying a table of data in a DataGrid
, and you want to let the user sort the data and change the sort order by clicking on the column headers.
Solution
Enable the DataGrid
control’s sorting features, and add custom coding to support the sorting along with an indication of the current sort column and order.
In the .aspx file, enable the DataGrid
control’s sorting features.
In the code-behind class for the page, use the .NET language of your choice to:
Create a data-binding method (
bindData
in our example) that does the following:Generates the SQL statement required to get the data from the database with an
ORDER BY
clause based on the value of thesortExpression
parameterFills a
DataTable
with the ordered data from the databaseOutputs an image indicating the sort column and sort order beside the current sort column heading
Call the data-binding method from the
Page_Load
method (to support the initial display of the grid) and from the event that is fired when the user clicks on a column header (thedgBooks_SortCommand
event in our example).
Figure 2-11 shows the appearance of a typical DataGrid
sorted by title in ascending order, the information in the first column. Examples 2-26, 2-27 through 2-28 show the .aspx and code-behind files for an example application that produces this result.
Figure 2-11. DataGrid ...
Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.