Thursday, February 10, 2011

Generic lists comparer - gridview sorting

Following is a good-code-snippet to sort the generic lists in C#.

Another snippet presented right below it can be used to sort the GridView in ASP .net.
-------------------------------------------------------------------------------------
public class GenericComparer<T> : IComparer<T>
{
    private SortDirection sortDirection;  
 
    public SortDirection SortDirection
    {
        get { return this.sortDirection; }
        set { this.sortDirection = value; } 
    }
 
    private string sortExpression; 
 
    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 (SortDirection == SortDirection.Ascending)
        {
            return obj1.CompareTo(obj2);
        }
        else return obj2.CompareTo(obj1); 
     }
}

--------------------------------------------------
Capture the "sorting" event of the ASP .NET gridview and put the following code in the event handler. You need to have the above GenericComparer class in order to make this work. Enjoi!

        private SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Ascending;
                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }
 
        protected void gvEvents_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
            }
 
            events.Sort(new GenericComparer<EWent.BusinessEntities.Event>(e.SortExpression, GridViewSortDirection));
            PopuplateEventsGridview();
        }
--------------------

No comments:

Post a Comment