Search code examples
c#sortinggridviewasp.net-4.0sortdirection

Asp.NET 4.0 GridView Default Sort Direction & Expression


Asp.net 4.0 gridView's built in support for "sort arrows" saves some code. All my grids are sorted by default when they're returned from the database, so it would seem logical that I should indicate which column is default sorted on by using the ASP.NET SortedDescendingHeaderStyle-CssClass etc.

ASP.NET doesn't decorate the default-sorted column magically: it has no way to know what order the SQL specifies. I can declaratively or programmatically decorate the appropriate header cell with the correct CSS class... but then ASP.NET doesn't remove it for me when I sort. So currently I am stripping this out by traversing the header cells looking for it on first "Sort" event. So I have a bit of code I run twice, once to add the arrow, and once on first manual sort to remove it. That's complicated, almost as much work as doing the whole job was before 4.0.

So... I must be missing something: is there some way to tell an ASP.NET GridView that it's contents are already sorted in a way which avoids having to manually add and then remove that sort indicator?


Solution

  • If you know your Sort Expression & direction You can Setit Explicitly by:

    GridView.Sort(expression, direction);
    

    expression would be list of columns "col1, col2, etc"