微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net – 对数据绑定集合或对象列表时对gridview进行排序

我有一个GridView设置如下:

>绑定到列表< T>在代码隐藏(我使用我自己的定制BOL)
>在HTML页面上没有DataSource对象
>可以在我选择的每一列上排序(SortExpressions都设置正确)

但是,我收到以下错误消息:

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

什么是我最好的方法来获得我的List< T>允许排序?

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

OnSorting = "MySortingMethod"

解决方法

感谢您的分类答案.我转向LINQ帮助动态排序.由于网格知道是否对ASC或DESC进行排序,哪个字段使用LINQ表达式.表达式执行排序,然后我简单地将这些结果绑定到我的gridview.

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

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

原文地址:https://www.jb51.cc/aspnet/249869.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐