From your question:"To show images by default so that users can know that they can click them to sort."
Add a HeaderStyle-CssClass property to your gridview, and put the default style in that property:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
AllowSorting="True"
OnSorting="GridView1_Sorting"
HeaderStyle-CssClass ="headRowSortable">
...and add corrosponding CSS with your Up-Down sortable icon:
.headRowSortable > th > a {
display: inline-block;
padding-left: 15px;
background: url('../Images/up-down-sort.png') left center no-repeat;
background-size: contain;
text-decoration: none;
vertical-align: central;
}
Which will work great as long as you are using an <asp:SQLDataSource>...which I am guessing you are.
As soon as you start binding the DataGrid to a Data Source in code, the GridView will stop applying the SortedAscendingHeaderStyle and SortedDescendingHeaderStyle because it won't know which column got sorted which way.
So in the case that you are doing your own data binding, you need to change the classes on the columns during the GridView_Sorting event:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//get the index of the column we sorted.
int iSortedColIdx = 0;
foreach (DataControlField c in GridView1.Columns)
{
if (c.SortExpression == e.SortExpression)
break;
iSortedColIdx++;
}
string sSortDirection = "";
if ((string)ViewState["SortColumn"] == e.SortExpression)
sSortDirection = ((string)ViewState["SortDirection"] == "") ? " DESC" : "";
else
ViewState["SortColumn"] = e.SortExpression;
ViewState["SortDirection"] = sSortDirection;
DataTable oDT = (DataTable)ViewState["MyDataSource"];
if (oDT.Rows.Count > 0)
{
string sSortString = e.SortExpression + sSortDirection;
oDT.DefaultView.Sort = sSortString;
GridView1.DataSource = oDT;
GridView1.DataBind();
// SET THE HEADER CSSCLASS AFTER THE DATA BIND. IT'LL GET CLEARED ON DATA BIND.
GridView1.HeaderRow.Cells[iSortedColIdx].CssClass = sSortDirection == "" ? "headRowSortAsc" : "headRowSortDesc";
}
}
... and the corrosponding css:
th.headRowSortAsc a {
display: inline-block;
padding-left: 15px;
background: url("../Images/down-sort.png") no-repeat;
background-size: 15px;
background-size: contain;
text-decoration: none;
vertical-align: central;
}
th.headRowSortDesc a {
display: inline-block;
padding-left: 15px;
background: url("../Images/up-sort.png") no-repeat;
background-size: 15px;
background-size: contain;
text-decoration: none;
vertical-align: central;
}