2011年1月21日星期五

Sort gridview that bind to a generic List in code behind

protected void clbgvTestForms_Sorting(object sender, GridViewSortEventArgs e)
{
IList tl = null;
if (IsPilot)
tl = TService.GetPilotTestList();
else
tl = TService.GetOperationalTestList();

if (tl != null)
{
var param = Expression.Parameter(typeof(tblTest), e.SortExpression);
var sortExpression = Expression.Lambda < Func < tblTest, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);

// If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.
// e.SortDirection is useless and unreliable (only works with SQL data source).
if (_sortBy == e.SortExpression)
_sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
else
_sortDirection = SortDirection.Ascending;

_sortBy = e.SortExpression;

if (_sortDirection == SortDirection.Ascending)
{
clbgvTestForms.DataSource = tl.AsQueryable().OrderBy(sortExpression);
}
else
{
clbgvTestForms.DataSource = tl.AsQueryable().OrderByDescending(sortExpression);
}
clbgvTestForms.DataBind();
}

}

_sortBy and _sortDirection are parameters which value is saved in viewstate.