I have a GridView with an ObjectDataSource
and I want to be able to sort it.
Paging works correctly, however Sorting gives me an exception:
The GridView
gridView
fired event Sorting which wasn't handled.
How do I enable sorting on the server side?
(i.e. gridView.EnableSortingAndPagingCallbacks
must remains false)
Set the gridView.AllowSorting property to true. From here the grid should allow you to sort data automatically on postback if you are using an object that implements IBindingList. However, since that is most likely not the case, you should take TheTXI's advice above and handle the sorting event yourself. Either wire the GridView.Sorting event in the codebehind, like so:
Handle the sorting inside the gridView_Sorting method, which should look like this:
Also, you can wire the event on the page itself using OnSort="gridView_Sorting" attached to the control.
Remember, since you are setting gridView.EnableSortingAndPagingCallbacks to false, this will not be immediately fired when the user tries to sort, it instead will wait for the postback to the server.
I hope this helps!
EDIT:
Since ObjectDataSource seems to be the middleman of choice, here is a brief explanation of wiring that for sorting as well. Use the following in your page (The full example can be found here on the MSDN, near the bottom):
Instead of actually using the gridView.Sorting event, you'll be jumping over to the ObjectDataSource to take care of the sorting. Once the sort is triggered it should call the method found in SelectMethod in your code behind. Then, inside SelectMethod, you would handle the rebuilding of your GridView object, which would look like:
You can use LINQ for this just use
OrderBy
on the selected column, do this:This is done in the
Select
method of the object data source.In the GridView add sort keys in it. And add
SelectParameter
in the object data source a `orderBy'It worked for me without changing the DAL layer and stored procedures.
I am using Linq2Sql and a ObjectDataSource and it does Paging and Sorting very well.
I implemented a Class to be used as the ObjectDataSource. It has a Select and a Count method calling my business layer which uses Linq2SQL queries to retrieve data from the DB. The select methods gets the first item index, page size and the sort expression as parameters automatically.
In the ASPX, the DataSource is configured like this:
The Select and the Count method use Linq queries to retrieve the data from the DB. I use the Skip(), Take() and Orderby() methods. For the OrderBy to accept a string sort expression I use DynamicLinq There is not much to code, Databinding, paging and Sorting are automatically working.
Pass
SortExpression
in method of Data Access Layer that callsStoredProcedure
and write below way SP to handle sorting on SQL. This way you can improve the performance of your sorting.Database SP: