views:

111

answers:

1

I've spent a good portion of my day fighting with GridView.Sort().

Nothing I did seemed to make it behave the way I would have expected. It wasn't until a coworker told me that within the expression you can specify the sort order for each term (except for the last one, apparently).

What is the purpose of supplying a sort direction if it's only applied to the last term in an expression containing multiple terms? For example:

GridView.Sort("Foo,Bar", SortDirection.Descending);

The term "Foo" in that expression will always be sorted in ascending order, while the term "Bar" has its sort order dictated by the SortDirection parameter of Sort(). However:

GridView.Sort("Foo DESC,Bar" SortDirection.Ascending);

The term "Foo" will now be sorted in descending order, and "Bar" in ascending order. I stumbled across this behaviour after the tip from my coworker when I tried this:

GridView.Sort("Foo DESC, Bar DESC", SortDirection.Descending);

An exception was thrown complaining that the column "Bar DESC" could not be found; this led me to believe that such expressions were not actually permissible. However, I was curious as to why no exception was thrown for "Foo DESC" (since it was listed first), so I tried this:

GridView.Sort("Foo DESC, Bar", SortDirection.Descending);

And finally saw the desired behaviour.

It appears as though I'm going to have to build the expression string manually since the sort order I need will vary on user input for the term "Foo", but remain consistent for the term "Bar". In all the searching I did I found no reference to this behaviour. Now that I understand how it works it makes sense that the first term is always ascending unless specified otherwise. But why not do away with the second parameter in Sort() and just leave the order (asc/desc) to the expression?

+1  A: 

Basically if the sort direction is descending, it adds DESC to the end, since ascending will never do this, you can just build your sort expression, set it to ascending and it'll effectively use only your first argument, like this:

GridView.Sort("Foo DESC, Bar DESC", SortDirection.Ascending);

I guess the majority of GridView sort cases are on a single column (and toggle asc/desc), that'd be the only reason I can think of for why the .Net team left the sorting this way.

I agree a .Sort(string sortExpression) should be there as well.

Nick Craver