1.11. Sorting Data Within a DataGrid
Problem
You are displaying a table of data and you want to let the user sort
the data in
a
DataGrid by clicking on its column headers.
Solution
Enable the DataGrid control’s
sorting features, and create a routine that binds the appropriate
data to the control when it is initially displayed and whenever the
user clicks a column header.
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 performs the actual sorting based on the value of asortExpressionparameter and binds a dataset to theDataGrid(this parameter is used in theORDER BYclause of the SQL statement).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 1-12 shows the appearance of a typical
DataGrid sorted by title, the information in the
first column. Example 1-30 through Example 1-32 show the .aspx and
code-behind files for an example application that produces this
result.

Figure 1-12. DataGrid with column sorting output
Discussion
The DataGrid control provides the basic plumbing required to support sorting. It will generate the links for the column headers that ...
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