Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

asp.net - 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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...