7

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!

7 Answers 7

9

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:

Sign up to request clarification or add additional context in comments.

2 Comments

How can your sort method handle sub-objects. Eg. you have an Order object which contains order.comment.rating, and you want to sort by the rating?
You'd have to manually walk the dots of the sortExpression passed in. Its pretty trivial to change the code to handle that.
2

http://msdn.microsoft.com/en-us/library/ms745786.aspx

https://web.archive.org/web/20210612115758/https://aspnet.4guysfromrolla.com/articles/012308-1.aspx

1 Comment

The MSDN article works great, except you need to change one line of code in the .cs file: string header = ((Binding)headerClicked.Column.DisplayMemberBinding).Path.Path; The way the code is on MSDN, sorting will only work if the header and column name are exactly the same.
0

more information on sorting in a gridview can be found here: MSDN Gridview sorting the methodology used to get the data should not matter, you can use the same sorting.

Comments

0

add:

  AllowSorting="true"

to the <asp:GridView /> tag, that should do it

1 Comment

If you just do this it gives an error The GridView 'GridView1' fired event Sorting which wasn't handled.
0

When I do that Alone it gives an error "The GridView 'GridView1' fired event Sorting which wasn't handled.

I've had that happen before... I've just created a throwaway handler, and then everything seemed to start working after that. Not the prettiest solution, but it worked for me.

That said, I didn't see any reference to a data source in your GridView code. You'll need something like this:

<asp:LinqDataSource ID="dsMyDataSource" runat="server"
DataContextTypeName="MyDataContext"
TableName="MyTable"
AllowSort="true" />

And then in your GridView:

<asp:GridView ID="gvMyGridView" runat="server" DataSourceID="dsMyDataSource" ... />

Comments

0

In the Properties Panel double Click on the Sorting Entry. A new Function will be created. In this Function write the Code to fill the Gridview. The only difference is to change the query based on GridViewSortEventArgs e

e.SortExpression and
e.SortDirection allways Ascending :-(

I hope this very short Answer helps

Comments

0

In Half Pseudocode for SQL Query

string Query= string.Empty;
string SortExpression = string.Empty;

// HDFSort is an HiddenField !!!

protected void SortCommand_OnClick(object sender, GridViewSortEventArgs e)
{
   SortExpression = e.SortExpression; 
   Query = YourQuery + " ORDER BY "+SortExpression +" "+ HDFSort.Value ;
   HDFSort.Value = HDFSort.Value== "ASC" ? "DESC" : "ASC";
   RefreshGridView();
}

protected void RefreshGridView()
{
   GridView1.DataSource = DBObject.GetData(Query);
   GridView1.DataBind();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.