When using a datagrid filled with statistics, it is useful to be able to sort the columns of the datagrid in ascending or descending order. Switching the sort direction of a column requires keeping track of the column that was last sorted and the direction it was sorted. Typically this is done by using datagrid custom attributes, which use ViewState, or by directly using custom ViewState properties. Both of these methods are basically the same. For an example of the first technique, see Effective Sorting in ASP.Net DatatGrids, or, for the second technique, see Sorting XML Data Using the .Net DataGrid.
Using ViewState is fine for a fairly small datagrid. However, with a medium or large-sized datagrid, the amount of ViewState data becomes large very quickly. The tables below show a comparison of the html output of a page having a medium-sized datagrid when the ViewState is enabled versus when it is not.
Page With ViewState Enabled |
|
Total |
ViewState |
Non-ViewState |
Characters |
20,696 |
14,875 |
5,821 |
Percent |
100 |
72 |
28 |
Page Without ViewState Enabled |
|
Total |
ViewState |
Non-ViewState |
Characters |
5,920 |
99 |
5,821 |
Percent |
100 |
2 |
98 |
The page that has a ViewState-enabled datagrid is almost four times larger than the page would be without it enabled. The page that has a ViewState-enabled datagrid will clearly take longer to render. When doing bidirectional sorting in a datagrid, ViewState is not necessary to keep track of the column and the direction. This information can be stored other ways. The code below shows an example of bidirectional sorting using session variables which eliminates the need for ViewState.
View Live Demo
View aspx Source
View aspx.cs Source
View XML Source
For another example of how ViewState could be avoided, see ASP.Net and Databases Part 7. This article, while not discussing ViewState, shows an example of using a radio button to indicate the direction of the sort. This method makes the use of ViewState unnecessary.
Of course, there may be good reasons to keep ViewState enabled. Without ViewState, the datagrid loses other capabilities, such as paging or using the edit column. Also, without ViewState, the datagrid has to be bound twice, first when the page loads and then again when the OnSort event fires.
However, in order to quickly render a medium-to-large datagrid that only needs sorting capabilities, it is worth considering disabling ViewState and using another method to hold sorting information.