您必須創建兩個視圖狀態,一個用於排序方向,另一個用於排序表達式,以便在排序時進行檢查。
首先,從gridview中檢索Sort Direction爲「Ascending」和「Descending」,並且當您想要在數據表中包含數據時,必須使用通過gridview排序方向的「ASC」和「DESC」在對數據進行排序時它是值得的。第二,一個翻轉功能,它將傳遞一個排序方向並將其翻轉,當它在第一次點擊時會被使用,例如第二次點擊它時,它會對「ASC」進行排序,它必須是「DESC」這就是爲什麼我翻轉它。
三,查看狀態用於保留上一類的值。
第四,創建一個viewstate來保存PageIndexChanging事件的排序數據表,當然你必須檢查viewstate是否爲null,那麼你將不得不提取數據並綁定它,否則你將不得不綁定gridview和排序數據表。
protected void GridView_Users_Sorting(object sender, GridViewSortEventArgs e)
{
if (String.IsNullOrEmpty(ViewState["sortExpression"].ToString()) && String.IsNullOrEmpty(ViewState["sortDirection"].ToString()))
{
//Sort and bind data as ASCENDING for the first time
DefaultSortBind(e);
}
else
{
if (ViewState["sortExpression"].ToString() == e.SortExpression.ToString())
{
string sortDirection = string.Empty;
if (ViewState["sortDirection"].ToString() == e.SortDirection.ToString())
{
sortDirection = flipSortDirection(GetSortDirection(e.SortDirection.ToString()));
}
else
{
sortDirection = GetSortDirection(e.SortDirection.ToString());
}
DataTable dt = new UserInfoTableTableAdapter().GetData();
dt.DefaultView.Sort = e.SortExpression + " " + sortDirection;
GridView_Users.DataSource = dt.DefaultView;
GridView_Users.DataBind();
ViewState["sortedDt"] = dt.DefaultView.ToTable();
ViewState["sortDirection"] = sortDirection;
}
else
{
//Sort and bind data as ASCENDING
DefaultSortBind(e);
}
}
}
private void DefaultSortBind(GridViewSortEventArgs e)
{
ViewState["sortExpression"] = e.SortExpression;
ViewState["sortDirection"] = e.SortDirection;
//Fetch data again, because if we try to get data from gridview it will give null
DataTable dt = new UserInfoTableTableAdapter().GetData();
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection.ToString());
GridView_Users.DataSource = dt.DefaultView;
GridView_Users.DataBind();
ViewState["sortedDt"] = dt.DefaultView.ToTable();
}
//Get sort direction
private string GetSortDirection(string sortDirection)
{
if (sortDirection == "Ascending")
{
return "ASC";
}
else
{
return "DESC";
}
}
//Flip sort direction
private string flipSortDirection(string sortDirection)
{
if (sortDirection == "ASC")
{
return "DESC";
}
else
{
return "ASC";
}
}
檢查這個帖子:http://stackoverflow.com/questions/7594375/sort-gridview-doesnt-work希望這幫助 – BizApps
謝謝,我想我的主要問題是,我可以使用當前數據表存儲在不知何故,或者我需要改變一個數據集來填充gridview呢? – rgvwed