Gridview Column sorting using Expression Tree
Does your project requires you to generate the Lamda expression at run time? Check out my resource. Here I have provided the code snippet to dynamically calculate the Lamda expression based on the grid columns.
This codesnippet helps the developer to construct the Lamda expression at runtime based on the columns of the Grid and sorting will take place based on that column name and its datatype.
Here, I have created a Employee List and bind it to the Gridview. Now each column of the Grid when clicked, the Grid will sort in descending order based on that column name and type.Design view page(EmployeeLINQ.aspx page)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmployeeLINQ.aspx.cs" Inherits="LINQApp.EmployeeLINQ" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="frmEmployee" runat="server">
<div>
<asp:GridView ID="grdEmployee" runat="server" AllowSorting="true" OnSorting="grdEmployee_OnSorting">
</asp:GridView>
</div>
</form>
</body>
</html>The code page(EmployeeLINQ.aspx.cs)
using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace LINQApp
{
public partial class EmployeeLINQ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Employee e1 = new Employee { Name = "Sumit", Age = 32, JoiningDate = DateTime.Parse("2008-01-02") };
Employee e2 = new Employee { Name = "John", Age = 34, JoiningDate = DateTime.Parse("2008-04-23") };
Employee e3 = new Employee { Name = "Merry", Age = 28, JoiningDate = DateTime.Parse("2011-02-17") };
Employee e4 = new Employee { Name = "Ana", Age = 30, JoiningDate = DateTime.Parse("2009-02-17") };
List<Employee> employees = new List<Employee>();
employees.Add(e1);
employees.Add(e2);
employees.Add(e3);
employees.Add(e4);
grdEmployee.DataSource = employees;
grdEmployee.DataBind();
Session["Employees"] = employees;
}
protected void grdEmployee_OnSorting(object sender, GridViewSortEventArgs ev)
{
var employees = Session["Employees"] as List<Employee>
if (employees != null)
{
string columnName = ev.SortExpression;
Type columnType = typeof(Employee).GetProperty(columnName).PropertyType;
List<Employee> sortedEmployeeList = typeof(DynamicLINQExtension).GetMethod("DynamicSort").MakeGenericMethod(new Type[] { typeof(Employee), columnType })
.Invoke(employees, new object[] { employees, columnName, "desc" }) as List<Employee>
grdEmployee.DataSource = sortedEmployeeList;
grdEmployee.DataBind();
Session["Employees"] = sortedEmployeeList;
}
}
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime JoiningDate { get; set; }
}
public static class DynamicLINQExtension
{
public static List<T> DynamicSort<T, TColumnType>(this IEnumerable<T> collection, string columnName, string sortDirection)
{
List<T> sortedlist = null;
IQueryable<T> query = collection.AsQueryable<T>();
ParameterExpression pe = Expression.Parameter(typeof(T), "t");
Expression<Func<T, TColumnType>> expr = Expression.Lambda<Func<T, TColumnType>>(Expression.Property(pe, columnName), pe);
if (!string.IsNullOrEmpty(sortDirection) && sortDirection == "desc")
{
sortedlist = query.OrderByDescending<T, TColumnType>(expr).ToList();
}
else
{
sortedlist = query.OrderBy<T, TColumnType>(expr).ToList();
}
return sortedlist;
}
}
}