来自您的问题:“默认显示图像,以便用户知道他们可以点击它们进行排序。”
将HeaderStyle-CssClass 属性添加到您的gridview,并将默认样式放在该属性中:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
AllowSorting="True"
OnSorting="GridView1_Sorting"
HeaderStyle-CssClass ="headRowSortable">
...并使用您的上下排序图标添加相应的 CSS:
.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;
}
只要您使用<asp:SQLDataSource>...,我猜您就是这样。
一旦您开始在代码中将 DataGrid 绑定到数据源,GridView 将停止应用 SortedAscendingHeaderStyle 和 SortedDescendingHeaderStyle,因为它不知道哪一列以哪种方式排序。
因此,如果您自己进行数据绑定,则需要在GridView_Sorting 事件期间更改列上的类:
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";
}
}
...以及相应的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;
}