数据绑定集合或对象列表时对网格视图进行排序 [英] Sorting a gridview when databinding a collection or list of objects

查看:19
本文介绍了数据绑定集合或对象列表时对网格视图进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按以下方式设置了 GridView:

I have a GridView set up in the following way:

  • 绑定到代码隐藏中的 List(我使用的是我自己的自定义 BOL)
  • HTML 页面上没有数据源对象
  • 可在我选择的每一列上排序(SortExpression 都设置正确)
  • 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:

GridView 'myGridView' 触发了未处理的事件排序.

The GridView 'myGridView' fired event Sorting which wasn't handled.

让我的 List 允许排序的最佳方法是什么?

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

我怀疑这与为 OnSorting 属性指定一个函数有关,即:

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

OnSorting = "MySortingMethod"

推荐答案

感谢您对排序的回答.我求助于 LINQ 来帮助动态排序.由于网格知道是对 ASC 还是 DESC 进行排序,以及哪个字段,因此我使用了 LINQ 表达式.表达式执行排序,然后我简单地将这些结果绑定到我的 gridview.

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.

我怀疑 jQuery 方法会更快,并且不需要完整的回发.

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

这篇关于数据绑定集合或对象列表时对网格视图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆