1.13. Combining Sorting and Paging in a DataGrid
Problem
You are implementing a
DataGrid with both
sorting and pagination, and you are having trouble making the two
features work together.
Solution
Enable the sorting features of the DataGrid
control, and add custom code to support the sorting along with an
indication of the current sort column and order (see Recipe 1.12 for details). Next, with pagination
enabled, add a small amount of custom code to track the sort column
and sort order so that they can be maintained between client round
trips and used any time rebinding is required. Figure 1-16 shows a typical DataGrid
with this solution implemented. Example 1-36
through Example 1-38 show the
.aspx file and code-behind files for an
application that produces this output.

Figure 1-16. Combining sorting and paging in a DataGrid output
Discussion
Getting both sorting and paging to work at the same time is a
notorious problem with a DataGrid. The key to
making it all work is to track the sort column and sort order so that
they can be used any time rebinding is required, whether because of a
page change or a sort command. Likewise, it is useful to put the sort
column and sort order data in the view state so that they are
properly maintained between client round trips.
The DataGrid provides the basic plumbing for
sorting and paging the data displayed in the grid. The
DataGrid also provides ...
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