2.10. Sorting Data in Ascending/Descending Order Within a DataGrid
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.
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 the
DataTablewith the ordered data from the database
Outputs 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 (the
dgBooks_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 ...