Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

sort columns of gridview in asp.net c#

Can anyone tell the function to sort the columns of a gridview in c# asp.net.

The databound to gridview is from datacontext created using linq. I wanted to click the header of the column to sort the data.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are 2 things you need to do to get this right.

  1. Keep the sorting state is viewstate(SortDirection and SortExpression)
  2. You generate the correct linq expression based on the current sorting state.

Manually handle the Sorting event in the grid and use this helper I wrote to sort by SortExpression and 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)

Check out my blog post on how to do this:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...