In my project, I am using a grid view and have to apply MultiColumn sorting on the column of the Gridview. I have used listDictionary to store all the applied sort expression and also used DataView to sort the gridview data as par the sorting.
The Code I wrote is :
public ListDictionary ld_SortExpression;
public ListDictionary SortExpression
{
get
{
ld_SortExpression = (ListDictionary)ViewState["SortExpressions"];
if (ld_SortExpression == null)
ld_SortExpression = new ListDictionary();
return ld_SortExpression;
}
set { ViewState["SortExpressions"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindControls();
}
}
protected void gvRemoval_Sorting(object sender, GridViewSortEventArgs e)
{
SaveSortState(e);
BindControls();
}
Private void BindControls()
{
DataSet ds = GetData(); 'GetData()gets the data from the database.
if (ds!= null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
gridView.DataSource= SortData(ds);
gridView.DataBind();
}
}
//Saves All the SortExpression and SortDirection in ListDictionary.
Private void SaveSortState(GridViewSortEventArgs e)
{
ld_SortExpression = SortExpression;
string sortDirection = string.Empty;
if (!ld_SortExpression.Contains(e.SortExpression))
ld_SortExpression.Add(e.SortExpression, e.SortDirection.ToString().Replace("Ascending", "ASC").Replace("Descending", "DESC"))
else
{
sortDirection = ld_SortExpression[e.SortExpression].ToString();
if (sortDirection == "ASC")
{
ld_SortExpression[e.SortExpression] = "DESC";
}
else if (sortDirection == "DESC")
ld_SortExpression.Remove(e.SortExpression);
}
SortExpression = ld_SortExpression;
}
//Sorts Data.
Private DataView SortData(DataSet ds)
{
DataTable dt = ds.Tables[0];
DataView dv = dt.DefaultView;
StringBuilder sbSortExpression = new StringBuilder();
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
if (SortExpression.Count > 0)
{
string[] myKeys = new string[SortExpression.Count];
SortExpression.Keys.CopyTo(myKeys, 0);
for (int i = 0; i <= SortExpression.Count - 1; i++) { sbSortExpression.Append(myKeys[i]); sbSortExpression.Append(" "); sbSortExpression.Append(SortExpression[myKeys[i]]); if (i != SortExpression.Count - 1) { sbSortExpression.Append(", "); } } dv.Sort = sbSortExpression.ToString(); } } return dv; }
-Arvind :)