How to sort using GridView and ObjectDataSource?

Jonathan Mitchem picture Jonathan Mitchem · Jun 16, 2009 · Viewed 27.9k times · Source

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)

Answer

Zensar picture Zensar · Jun 16, 2009

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:

gridView.Sorting += new GridViewSortEventHandler(gridView_Sorting); 

Handle the sorting inside the gridView_Sorting method, which should look like this:

private void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
     //Sorting logic here
}

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):

<asp:GridView ID="TestGridView" runat="server" DataSourceID="ObjectDataSourceTest"
        AllowSorting="True">
    </asp:GridView>
    <asp:ObjectDataSource ID="ObjectDataSourceTest" runat="server" 
        SelectMethod="SelectMethod" 
        TypeName="Samples.AspNet.CS.SortingData" 
        SortParameterName="sortExpression">
    </asp:ObjectDataSource>

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:

public void SelectMethod(string sortExpression)
{
     //Rebuild gridView table if necessary, same method used in 
     //on a postback, and retrieve data from the database. Once
     //completed sort the data with:

     gridView.Sort(sortExpression, SortDirection.(Ascending or Descending))
}