【发布时间】:2016-09-28 09:07:33
【问题描述】:
我有一种情况,当我第一次单击我的 gridview 的 ItemID 标题进行降序排序时,它仍然保持升序排序。只有在第二次单击时,它才会进行降序排序。这是我的代码:
protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
this.ViewState["SortExpression"] = "ItemID";
this.ViewState["SortDirection"] = "ASC";
BindMyGrid();
}
public void BindMyGrid()
{
string sortExpression = this.ViewState["SortExpression"].ToString();
string sortDirection = this.ViewState["SortDirection"].ToString();
string strsql = "SELECT * FROM [MasterTbl] ORDER BY " + sortExpression + " " + sortDirection + "";
MyDataSource.SelectCommand = strsql;
}
protected void MyGridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = this.ViewState["SortExpression"].ToString();
string sortDirection = this.ViewState["SortDirection"].ToString();
if (sortExpression == e.SortExpression)
{
this.ViewState["SortDirection"] = (sortDirection == "ASC") ? "DESC" : "ASC";
}
else
{
this.ViewState["SortExpression"] = e.SortExpression;
this.ViewState["SortDirection"] = "ASC";
}
this.BindMyGrid();
}
HTML 代码:
<asp:GridView ID="MyGridView" runat="server" CssClass="table table-striped table-bordered table-hover" AutoGenerateColumns="False"
DataSourceID="MyDataSource" AllowPaging="true" onpageindexchanging="MyGridView_PageIndexChanging" OnRowDataBound="MyGridView_RowDataBound"
AllowSorting="true" OnSorting="MyGridView_Sorting" OnRowCreated="MyGridView_RowCreated">
<Columns>
<%--Here is where my Boundfield columns are--%>
<Columns>
<PagerStyle CssClass="pagination-ys" />
</asp:GridView>
<asp:SqlDataSource ID="MyDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:DBCS %>"
</asp:SqlDataSource>
真正让我困惑的是,当我进入调试模式时,strsql 会返回
SELECT * FROM [MasterTbl]
ORDER BY ItemID DESC
在第一次点击时,但实际上并不会强制它按降序排列。然后在第二次单击时,它将返回
SELECT * FROM [MasterTbl]
ORDER BY ItemID ASC
然后它按降序排列。
【问题讨论】:
-
Page_Load中关于数据源和 GridView 之间的数据绑定是否发生了什么? -
没有。绑定仅在 SelectedIndexChanged 事件中发起。
-
如果你改变了排序列,你是否有同样的行为(排序表达式回发太晚了)?
-
是的,如果我对另一列执行此操作,也会发生同样的事情。我将排序表达式更改为另一个名为 Description 的列,并且发生了同样的事情。
-
我认为我们需要更多信息(抱歉)。你能显示数据源的标记吗?以及 GridView 的标记(不是内部细节,但至少与
<asp:GridView ...一致)。
标签: c# asp.net sorting gridview