Add an icon in the header of ASP.NET GridView to show sort mode of the column
This example shows how to add an icon to the title of the columns in a GridView, to display the sort direction
In the markup file
....
<div>
<asp:GridView runat="server"
ID="GridViewCustomers"
AllowSorting="True"
AutoGenerateColumns="False"
DataSourceID="AccessDataSourceCustomers"
OnRowCreated="GridViewCustomers_RowCreated" >
<Columns>
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
</Columns>
<HeaderStyle BackColor="#016AB4" ForeColor="White" HorizontalAlign="Left"></HeaderStyle>
</asp:GridView>
<asp:AccessDataSource runat="server"
ID="AccessDataSourceCustomers"
DataFile="~/App_Data/Northwind.mdb"
SelectCommand="SELECT [CompanyName], [ContactName], [City], [Country] FROM [Customers] ORDER BY [CompanyName]"></asp:AccessDataSource>
</div>
...
In the code-behind file that contains GridViewCustomers_RowCreated
/// <summary>
/// Adds an icon next to the title of the column to display the sort direction
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridViewCustomers_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell tc in e.Row.Cells)
{
if (tc.HasControls())
{
LinkButton lb = (LinkButton)tc.Controls[0];
if (lb != null)
{
Image icon = new Image();
icon.ImageUrl = "~/images/sort-" + (GridViewCustomers.SortDirection == SortDirection.Ascending ? "asc" : "desc") + ".png";
if (GridViewCustomers.SortExpression == lb.CommandArgument)
{
tc.Controls.Add(new LiteralControl(" "));
tc.Controls.Add(icon);
}
}
}
}
}
}
In the images folder are two files sort-asc.png and sort-desc.png
Here is the result for the sample: