How to do Sorting gridview columns using linq ?
Sorting for existing data set using LINQ.
Using Generinc Comparer class we can sort class object using LINQ.
1) Add 'GenericComparer.cs” class
public class GenericComparer<T>
: IComparer<T>
{
private SortDirection
_sortDirection;
private string
_sortExpression;
/// <summary>
/// Direction in which to sort.
/// </summary>
public SortDirection
GenericSortDirection
{
get { return this._sortDirection; }
set { this._sortDirection = value; }
}
public GenericComparer(string sortExpression, SortDirection sortDirection)
{
this._sortExpression = sortExpression;
this._sortDirection = sortDirection;
}
public int Compare(T x, T
y)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(_sortExpression);
IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
if (GenericSortDirection == SortDirection.Ascending) return obj1.CompareTo(obj2);
else return
obj2.CompareTo(obj1);
}
}
Add Following Code into GridView Sort Event:
Add Following Code into GridView Sort Event:
2) Create Object List as Static:
static List<Projects> objProjectsList = new List<Projects>();
3) Bind Object List:
objProjectsList = DataSouce;
4) Sort Gridview Event code:
protected void
gvHeader_Sorting(object sender, GridViewSortEventArgs e)
{
SortDirection sortdirection;
if (ViewState["SortDirection"] != null && ViewState["SortDirection"].ToString() == "Ascending")
sortdirection = SortDirection.Descending;
else
sortdirection = SortDirection.Ascending;
objProjectsList.Sort(new GenericComparer<Projects>(e.SortExpression, sortdirection));
gvHeader.DataSourceID = null;
gvHeader.DataSource = listProjectTask;
gvHeader.DataBind();
ViewState["SortDirection"] = sortdirection.ToString();
}
No comments:
Post a Comment