Monday, July 09, 2012

Grid Sorting

using System;


using System.Collections.Generic;

using System.Text;

using SunTrust.DemandDelivery.Entity;

using System.Web.UI.WebControls;

namespace SunTrust.DemandDelivery.Entity

{

public class EmployeeComparer : IComparer

{



string memberName = string.Empty;

SortDirection sortOrder = SortDirection.Ascending;



public EmployeeComparer(string strMemberName, SortDirection sortingOrder)

{

memberName = strMemberName;

sortOrder = sortingOrder;

}



#region IComparer Members



public int Compare(Employee dItem1, Employee dItem2)

{

int returnValue = 1;

switch (memberName)

{

case "EmployeeNo":

if (sortOrder == SortDirection.Ascending)

{

returnValue = dItem1.EmployeeNo.CompareTo(dItem2.EmployeeNo);

}

else

{

returnValue = dItem2.EmployeeNo.CompareTo(dItem1.EmployeeNo);

}

break;

case "OrgDateofRequest":

if (sortOrder == SortDirection.Ascending)

{

returnValue = dItem1.OrgDateofRequest.CompareTo(dItem2.OrgDateofRequest);

}

else

{

returnValue = dItem2.OrgDateofRequest.CompareTo(dItem1.OrgDateofRequest);

}

break;

default:

if (sortOrder == SortDirection.Ascending)

{

returnValue = dItem1.ID.CompareTo(dItem2.ID);

}

else

{

returnValue = dItem2.ID.CompareTo(dItem1.ID);

}

break;

}

return returnValue;

}



#endregion





}

}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)


{

EmployeeBAO activeEmployeeBAO = new EmployeeBAO();

List list = activeEmployeeBAO.GetAllRecord();



//get the current column details

string strColumnName = e.SortExpression;

SortDirection strSortOrder = getSortOrder();

list.Sort(new EmployeeComparer(strColumnName, strSortOrder));

GridView1.DataSource = null;

GridView1.DataSource = list;

//customizeDataGridView();

//GridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = strSortOrder;







//list.Sort(new GenericComparer(e.SortExpression, e.SortDirection));

//GridView1.DataSource = list;

GridView1.DataBind();

}



private SortDirection getSortOrder()

{

if (CurrentSortDirection == SortDirection.Ascending)

CurrentSortDirection = SortDirection.Descending;

else

CurrentSortDirection = SortDirection.Ascending;



return CurrentSortDirection;

}



private SortDirection CurrentSortDirection

{

get

{

if (ViewState["SortDirection"] == null)

ViewState["SortDirection"] = SortDirection.Ascending;

return (SortDirection)ViewState["SortDirection"]; }

set

{

ViewState["SortDirection"] = value;

}

}

No comments: