AllowSorting and ViewState
Im working through a bug fix round on an ASP.NET project that I’ve had for a while. One of the issues that we found was that all of the sudden, when turning ViewState off, the Sort functionality stopped working on a particular datagrid that we had. We had to leave ViewState off, because of the sheer amount of data that was being put into the grid was causing timeouts when the page was loading and other issues.
Interestingly enough, it seems that if you turn the view state off, you need to rebind the grid to get sorting to work. Ultimately, this means that you’re binding the grid twice.
I had all my code inside of an if (!Page.IsPostBack) block, so the fix was simple enough. Im just wondering about performance. Is it that much more expensive to bind twice?
We’ve been dealing with this pain for a long time now, so I can very well relate to your story. I’m afraid if you want a sorting and paging DataGrid you have to enable view state, and yes, you have to bind twice on postback whenever you sort or page it. It’s inefficient, but I don’t think there’s a way around it.
In my article on view state (pardon this shameless plug) I wrote:
“Remember, DataGrid renders as a table with rows and cells being its child controls. View state is maintained for these child controls. The DataGrid has no memory of the data source you bound it to! The datasource is NOT stored in the viewstate.” (http://www.aspnetresources.com/articles/ViewState.aspx)
Also, a couple of years ago Dino Esposito wrote:
“Doing without view state is difficult whenever state information can’t be dynamically inferred. For example, if you want to track the sort order of a pageable DataGrid you can cache it only in the view state” (http://msdn.microsoft.com/msdnmag/issues/03/02/CuttingEdge/)
I’m a big proponent of cutting view state to the bone, but DataGrid controls don’t cooperate that well.
Here is how I’m fixing it
At the bottom of my sort sub I have some code like
ViewState(”ImSorting”) = “True”
Then in my pageload I have on the post back
If CStr(ViewState(”ImSorting”)) = “True” Then
ViewState(”ImSorting”) = “False”
Else
BindGrid()
End If
The sort goes first binds the grid and flags it as not needing to be bound and all the postback does is reset the flag. This gets rid of the extra bind.
I got to thinking about it after I posted and came up with an even easier way to prevent the extra bind.
Use some code like this in your post back
If Request.Form.Get(”__EVENTARGUMENT”) = “” Then
BindGridFunction()
End If
Should be the only code you need. This property is going to be empty if there is no sorting / paging going on. If there is something in there then you must of sorted or paged or something.
If your grid has a lot going on you might have to look at the argument to see what you should do.


