I really do not get it.

I've worked more with the ASP.NET MVC Framework but less with WebForms. I have googled alot about how to sort on GridView but mostly it ends up using the Session or the ViewState which I do not prefer.
Instead, this how-to explains how it should work but it does not work for me.

It ends up that

  1. after clicking on a column name and doing the postback the gridview stays in the same sorting as before.
  2. GridViewSortEventArgs.SortDirection is always "Ascending" (there are also some threads about that behavior)

Do you have any idea how it could/should work as explained in the how-to mentioned above and without using Session/ViewState? Or maybe the how-to is just not working at all?

Kind regards

Update 1:
The question is more general and also related to the how-to, not to my implementation.
My implementation is not different than in the how-to.
Some more things to mention:
- I am forced to use the ASP.NET 3.5 framework
- In my implementation, I have created a simple GridView in a user control (.ascx file) which contains that logic in code-behind and then loaded that user control on a simple, empty page (.aspx file).

Maybe can anyone confirm if the how-to works for him?

2

There are 2 best solutions below

0
On

From what I understand, you can manipulate the underlying result set if you load your results into a DataView

http://msdn.microsoft.com/en-us/library/system.data.dataview%28v=vs.110%29.aspx

With a DataView, you can set the sort direction and then bind that DataView to the grid. The reason people use Session or ViewState is to toggle between postbacks what the user has selected as their sort.

The only other way you can track which direction the user is sorting by, that I can think of without fetching from an external data source, is by using Request.Querystring

I've never had luck with GridView sorting and have always resulted to using a DataView with a sort to get sorts to work properly.

0
On

There is no purpose for the GridViewSortEventArgs.SortDirection! It was a feature that (as far as I know) was never implemented fully by Microsoft: it always returns Ascending, all the time. Therefore, everyone has come up with their own favorite workaround for the lack of support for bi-directional gridview sorting! I know it seems strange to hear that there is a property there that simply does not get used, but that is the truth as far as I know!

Here are a lot of workarounds for the problem of why the sort direction is always ascending... GridView sorting: SortDirection always Ascending

Personally, I prefer my own solution, which does NOT use ViewState or Session, but rather plain old vanilla hidden fields! Hidden fields are very "cheap" in my opinion, since I always turn off ViewState for all WebForm projects... Here is a link to the hidden field solution:

https://stackoverflow.com/a/25657044/796858