1.12. 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 sorting features of the DataGrid
control and add custom coding to support the sorting along
with an indication of the current sort column and order. An example
of the output that is possible with this approach is shown in Figure 1-15. Example 1-33 through
Example 1-35 show the .aspx file
and code-behind files for an application that produces this output.

Figure 1-15. DataGrid with ascending/descending sorting output
Discussion
To add sorting to a DataGrid control, you must
first enable its sorting features by setting the
AllowSorting attribute of the
DataGrid element to True. In
addition, set the SortExpression attribute of the
asp:BoundColumn element to the expression that
will be used in your code to perform the sorting. See Recipe 1.11 for details on these steps.
Next, remove the HeadingText attribute in the
asp:BoundColumn element. You will want to set the
heading text in the code-behind, so it is not needed in the
.aspx file.
To support sorting in both ascending and descending order as well as visually indicating the sort order requires a bit more code in the code-behind class. This is driven by needing to know the current sort column and ...
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