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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/aspnet/249869.html

猜你在找的asp.Net相关文章