[ Download Code ]
One more important aspect of this example is to display the current sorting order in the DataGrid header in a manner that is easy to recognize visually. This is accomplished by inserting an image and number next to the sorted column.
This is implemented in the ItemDataBound event handler of the DataGrid when binding the header item.
private void dgEmployee_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
if (dgEmployee.Attributes["SortExpression"] != String.Empty)
DisplaySortOrderImages(dgEmployee.Attributes["SortExpression"] ,e.Item);
}
}
Listing 6
The method DisplaySortOrderImages loops through the cells of the header item. If any of the cells contain a link button, it then looks up its command argument (which is same as that columns sort expression) within the DataGrid’s SortExpression attribute and inserts an image and a literal (for the sequence number) next to the cell.
private void DisplaySortOrderImages(string sortExpression,DataGridItem dgItem)
{
string[] sortColumns = sortExpression.Split(",".ToCharArray());
for (int i=0; i< dgItem.Cells.Count; i++)
{
if(dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton)
{
string sortOrder;
int sortOrderNo;
string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument;
SearchSortExpression(sortColumns,column,out sortOrder,out sortOrderNo);
if (sortOrderNo > 0)
{
if (sortOrder.Equals("ASC"))
{
Image imgUp = new Image();
imgUp.ImageUrl = "~/images/sortascending.gif";
dgItem.Cells[i].Controls.Add(imgUp);
Literal litOrder = new Literal();
litOrder.Text = sortOrderNo.ToString();
dgItem.Cells[i].Controls.Add(litOrder);
}
else if (sortOrder.Equals("DESC"))
{
Image imgDown = new Image();
imgDown.ImageUrl = "~/images/sortdescending.gif";
dgItem.Cells[i].Controls.Add(imgDown);
Literal litOrder = new Literal();
litOrder.Text = sortOrderNo.ToString();
dgItem.Cells[i].Controls.Add(litOrder);
}
}
}
}
}
private void SearchSortExpression(string[] sortColumns,string sortColumn,
out string sortOrder,out int sortOrderNo)
{
sortOrder = "";
sortOrderNo = -1;
for (int i=0; i< sortColumns.Length; i++)
{
if (sortColumns[i].StartsWith(sortColumn))
{
sortOrderNo = i+1;
sortOrder = sortColumns[i].Substring(sortColumn.Length).Trim();
}
}
}
Listing 7
Conclusion
To summarize, we've taken advantage of the DataView's sorting capabilities to implement multi-column sorting on the DataGrid. Full source code is included in the downloadable sample. It also shows how to write the sort expression to the browser status bar by registering a client-side Javascript function. Enjoy, and be sure to let me know if you find this article applicable to your project scenario.