在asp.net中排序gridview的列c#

前端之家收集整理的这篇文章主要介绍了在asp.net中排序gridview的列c#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
任何人都可以告诉函数在c#asp.net中对gridview的列进行排序.

gridview的数据绑定来自使用linq创建的datacontext.我想单击列的标题来对数据进行排序.

谢谢!

解决方法

要做到这一点,您需要做两件事.

>保持排序状态为viewstate(SortDirection和SortExpression)
>您可以根据当前的排序状态生成正确的linq表达式.

手动处理网格中的Sorting事件并使用我编写的这个帮助器按SortExpression和SortDirection排序:

public static IQueryable<T> SortBy<T>(IQueryable<T> source,string sortExpression,SortDirection direction) {
    if (source == null) {
        throw new ArgumentNullException("source");
    }

    string methodName = "OrderBy";
    if (direction == SortDirection.Descending) {
        methodName += "Descending";
    }

    var paramExp = Expression.Parameter(typeof(T),String.Empty);
    var propExp = Expression.PropertyOrField(paramExp,sortExpression);

    // p => p.sortExpression
    var sortLambda = Expression.Lambda(propExp,paramExp);

    var methodCallExp = Expression.Call(
                                typeof(Queryable),methodName,new[] { typeof(T),propExp.Type },source.Expression,Expression.Quote(sortLambda)
                            );

    return (IQueryable<T>)source.Provider.CreateQuery(methodCallExp);
}

db.Products.SortBy(e.SortExpression,e.SortDirection)

查看my blog post 如何执行此操作:

原文链接:https://www.f2er.com/aspnet/251416.html

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