当前位置:  开发笔记 > 后端 > 正文

在对数据集或对象列表进行数据绑定时对网格视图进行排序

如何解决《在对数据集或对象列表进行数据绑定时对网格视图进行排序》经验,为你挑选了1个好方法。



1> p.campbell..:

感谢您对排序的答案.我转向LINQ以帮助动态排序.由于网格知道是否要对ASC或DESC进行排序,以及哪个字段,我使用了LINQ表达式.Expression执行了排序,然后我简单地将这些结果绑定到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 myGridResults = PerfomSearch();


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


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


        myGridView.DataBind();
    }
}


@p.campell:稍微修改了方法,因为GridView`e.SortDirection`总是返回`SortDirection.Ascending`.希望你不要介意
推荐阅读
linjiabin43
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有