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 (
bindDatain our example) that does the following:Generates the SQL statement required to get the data from the database with an
ORDER BYclause based on the value of thesortExpressionparameterFills a
DataTablewith 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_Loadmethod (to support the initial display of the grid) and from the event that is fired when the user clicks on a column header (thedgBooks_SortCommandevent 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access