Sorting a gridview when databinding a collection or list of objects

I have a GridView set up in the following way:

  • bound to a List<T> in code-behind (I am using my own custom BOL)
  • no DataSource Object on the HTML page
  • sortable on each column that I choose (the SortExpressions are all set correctly)

However, I am getting the following error message:

The GridView ‘myGridView’ fired event Sorting which wasn’t handled.

What is the best way for me to get my List<T> to allow sorting?

I am suspecting that it will have to do with specifying a function for the OnSorting attribute, i.e.:

OnSorting = "MySortingMethod"

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Thank you for your answers on the sorting. I turned to LINQ to help sort dynamically. Since the grid knows whether to sort ASC or DESC, and which field, I used a LINQ Expression. The Expression performed the sorting, and then I simply bound those results to my gridview.

I suspect the jQuery method would be faster, and wouldn’t require a full postback.

using System.Linq.Expressions;

public SortDirection GridViewSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null)
            ViewState["sortDirection"] = SortDirection.Ascending;

        return (SortDirection)ViewState["sortDirection"];
    }
    set { ViewState["sortDirection"] = value; }
}

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
    //re-run the query, use linq to sort the objects based on the arg.
    //perform a search using the constraints given 
    //you could have this saved in Session, rather than requerying your datastore
    List<T> myGridResults = PerfomSearch();


    if (myGridResults != null)
    {
        var param = Expression.Parameter(typeof(T), e.SortExpression);
        var sortExpression = Expression.Lambda<Func<T, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);


        if (GridViewSortDirection == SortDirection.Ascending)
        {
            myGridView.DataSource = myGridResults.AsQueryable<T>().OrderBy(sortExpression);
            GridViewSortDirection = SortDirection.Descending;
        }
        else
        {
            myGridView.DataSource = myGridResults.AsQueryable<T>().OrderByDescending(sortExpression);
            GridViewSortDirection = SortDirection.Ascending;
        };


        myGridView.DataBind();
    }
}

Method 2

Correct – you will need to handle the onsorting, sort your list and re-bind.

Alternatively you could look at handling the sorting client side using a javascript framework like jQuery.

Method 3

If you get this error:

the datasource does not support server side paging

Try adding .ToList<T>() to your query:

if (e.SortDirection == SortDirection.Ascending)
{
    GridViewTrackerLoans.DataSource = myGridResults.AsQueryable<T>().OrderBy(sortExpression).ToList<T>();
}
else
{
    GridViewTrackerLoans.DataSource = myGridResults.AsQueryable<T>().OrderByDescending(sortExpression).ToList<T>();
};

Method 4

You could write a Compare for your objects:

private int CompareObject(YourObject object1, YourObject object2)
{
    int iReturnValue = 0;
    if ((object1 != null) && (object2 != null) &&
        (object1.SomeField != object2.SomeField))
    {
        iReturnValue = (object1.SomeField > object2.SomeField) ? 1 : -1;
    }
    return iReturnValue;
}

Then when in your sorting event just pass in the Compare function into your objects sort routine (assuming you have something like List).
// Your list of data from the session or viewstate or whereever you have it stored.
lstObjects.Sort(CompareObject);

You now have a sorted list so just rebind it.

Method 5

Correct, you need to handle the OnSorting event and set the AllowSorting property to true.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x