I have seen some questions regarding how to add an up and down image to a GridView header columns when sorting is enabled. I though this could be interesting for some of you so I have created a simple example that is added to this post. If someone has a better solution, please let me know and share it with us all.
The following code will add an image to the header columns of the GirdView control and will display an up or down arrow depends on how the GridView is sorted:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script runat="server">
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row != null && e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
if (cell.HasControls())
{
LinkButton button = cell.Controls[0] as LinkButton;
if (button != null)
{
Image image = new Image();
image.ImageUrl = "default.gif";
if (GridView1.SortExpression == button.CommandArgument)
{
if (GridView1.SortDirection == SortDirection.Ascending)
image.ImageUrl = "asc.gif";
else
image.ImageUrl = "desc.gif";
}
cell.Controls.Add(image);
}
}
}
}
}
</script>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" AllowSorting="True" DataKeyNames="PageId" AutoGenerateColumns="False" OnRowCreated="GridView1_RowCreated">
<Columns>
<asp:BoundField HeaderText="PageId" DataField="PageId"></asp:BoundField>
<asp:BoundField HeaderText="ParentPage" DataField="ParentPage" SortExpression="ParentPage"></asp:BoundField>
<asp:BoundField HeaderText="Title" DataField="Title" SortExpression="Title"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [PageId], [ParentPage], [Title] FROM [Pages]" ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
If you take a look at the code above, you can see that I have removed the SortExpression attribute from the PageId column. I have done that because I don’t want to sort the grid based on that column. I have only removed the SortExpression to show you how you can disable the sorting of one column (The template field has also a SortExpression attribute).