[英]ASP.NET Gridview not sorting on first click
我有一種情況,當我第一次單擊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
但隨后它以降序排列。
我已復制了問題,並嘗試了很多事情,才能正確的行為,同時保持DataSourceID="MyDataSource"
中的聲明MyGridView
,沒有成功。
使它起作用的唯一方法是從GridView的標記中刪除DataSourceID
屬性,並在后面的代碼中設置數據源:
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;
MyGridView.DataSource = MyDataSource;
MyGridView.DataBind();
}
這就是我將數據源與數據綁定控件一起使用的方式,而我從未經歷過問題中描述的奇怪行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.