Friday, March 26, 2010

Gridview SortExpression and SortDirection not being set

I was doing a lot of manual binding to a Gridview and tried to implement a sort. This is no easy task without using some type of ObjectDataSource, but I made it to a point where I had it working except the actual SortExpression and SortDirection didn't seem to be set.

A quick google search turned out others complaining of the same problem and complaining that SortExpression and SortDirection were Get only properties. A quick hit of System.Reflection let me set those values with:


typeof(GridView).GetField("_sortExpression", BindingFlags.NonPublicBindingFlags.Instance).SetValue(this.gvSearchResults, e.SortExpression);

typeof(GridView).GetField("_sortDirection", BindingFlags.NonPublic BindingFlags.Instance).SetValue(this.gvSearchResults, e.SortDirection);


Doing this turned up the real problem. My DataSource was not considered Sortable and setting those fields caused the Gridview to attempt to sort it, thus throwing an exception.

The only solution I've come up with in this case is to manage the SortExpression and SortDirection in Viewstate myself and display images/do datasource sorting with my own code.

0 comments: