1. Add using statement:
using System.Linq.Expressions; 2. Define your gridview and set the event “onsorting”.
<asp:GridView ID="myGridView" runat="server"...
onsorting="gridView_Sorting">
3. Set up your sorting method:
protected void gridView_Sorting(object sender, GridViewSortEventArgs e){
//Get the datasource and last sortDirection (enum (int) in this case):
List<YourObject> yourObjects = CurrentDataSource;
int currentSortDirection = CurrentSortDirection;
if (yourObjects != null)
{
//Use the e.SortExpression to order the list of objects
var param = Expression.Parameter(typeof(YourObject), e.SortExpression);
var sortExpression = Expression.Lambda<Func<YourObject, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);
//Set the list ordered ascending as datasource
if (currentSortDirection == (int)SortDirection.ascending)
{
myGridView.DataSource = yourObjects.AsQueryable<YourObject>().OrderBy(sortExpression);
}
//Set the list ordered descending as datasource
else
{
myGridView.DataSource = yourObjects.AsQueryable<YourObject>().OrderByDescending(sortExpression);
}
if (currentSortDirection == (int)SortDirection.ascending)
CurrentSortDirection = (int)SortDirection.descending;
else
CurrentSortDirection = (int)SortDirection.ascending;
myGridView.DataBind();
}
}
4. Your all set. Good luck.
This is one of the best solutions I've seen so far that doesn't involve a lot of jumping through hoops in order to set up a special IComparer class just for the sorting of your GridView.
ReplyDeleteOne question, though: where do you get and store the CurrentSortDirection? You pull that value out of the air above. The value in e.SortDirection shows the direction for the current sort, but I don't know how to tell the GridView what the next sort direction should be.
Thanks!
This comment has been removed by the author.
DeleteHi Derek,
DeleteIn this sample I've put CurrentSortDirection as a property in session. Now you can choose whatever suits you most as long as you keep CurrentSortDirection persistent (post backs) eg. Session, ViewState, control attribute, hidden fields..
Good to hear you liked it.
Perfect!! But I must add .ToList() to .myGridView.DataSource
ReplyDelete