Skip to content

ASP.Net DataGrid Sort Indicator

Talk about a pain. You’d think this would be easier….

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private void Grid_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
	DataGrid grid = (DataGrid)source;
	grid.DataSource = CurrentView;
	bool isAsc;
	if (((DataView)grid.DataSource).Sort != e.SortExpression)
	{
		((DataView)grid.DataSource).Sort = e.SortExpression;
		isAsc = true;
	}
	else
	{
		((DataView)grid.DataSource).Sort += " DESC";
		isAsc = false;
	}
 
	//Loop columns to find sort
	foreach(DataGridColumn col in grid.Columns)
	{
		//Clear header of previous images
		col.HeaderText = col.HeaderText.Replace("<img src="http://john.rozeske.com/wp-admin/Images/SortDsc.gif" alt="Desc" class="sort" />","").Replace("<img src="http://john.rozeske.com/wp-admin/Images/SortAsc.gif" alt="Asc" class="sort" />","");
		// Find the right column
		if(e.SortExpression.ToLower().CompareTo(col.SortExpression.ToLower()) == 0)
		{
			if(isAsc)
			{
				col.HeaderText = col.HeaderText + "<img src="http://john.rozeske.com/wp-admin/Images/SortAsc.gif" alt="Asc" class="sort" />";
			}
			else
			{
				col.HeaderText = col.HeaderText + "<img src="http://john.rozeske.com/wp-admin/Images/SortDsc.gif" alt="Desc" class="sort" />";
			}
		}
	}
 
	//Bind the grid data
	grid.DataBind();
}

Post a Comment

Your email is never published nor shared. Required fields are marked *