In pretty much every web application I build, I come across the problem that the default sorting mechanism build in to gridview, doesn’t work when binding to List objects. It requires the gridview to be bound to a dataset object instead of a List.
While searching the web for a solution, I came across a great post on stackoverflow: Sorting a gridview when databinding a collection or list of objects . The post provides some really nice code, using expression trees, to determine the sort column at runtime. As this code works really nice, I’ll repost it here. I updated it somewhat, cause the original poster didn’t account for the fact the GridViewSortEventArgs object always returns the same sortdirection (SortDirection.Ascending)
private void OnGridViewSort(object sender, GridViewSortEventArgs e)
{
List<Product> prl = m_Provider.GetAllProducts();
if (prl != null)
{
var param = Expression.Parameter(typeof(Product), e.SortExpression);
var sortExpression = Expression.Lambda<Func<Product, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);
SortDir = (ViewState["SortDirection"] == null) ? SortDir = SortDirection.Ascending : (SortDirection)ViewState["SortDirection"];
if (!string.IsNullOrEmpty(e.SortExpression))
{
if (e.SortExpression.Equals(this.SortExpression))
{
SortDir = (SortDir == SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
ViewState["SortDirection"] = SortDir;
}
this.SortExpression = e.SortExpression;
}
if (SortDir == SortDirection.Ascending)
{
m_GridView.DataSource = prl.AsQueryable<Product>().OrderBy(sortExpression);
}
else
{
m_GridView.DataSource = prl.AsQueryable<Product>().OrderByDescending(sortExpression);
}
m_GridView.DataBind();
}
}
Hope someone benifits from this!
Rinze