大家好我在排序gridview时遇到了麻烦。假设我的gridview有10行数据和2列,Name和Age。分页设置为每页5行数据。当我点击名称时,它被正确排序。但是,当我点击下一页时,它再次变为“未排序”。请帮忙!我已在下面附上了事件处理程序。
protected void SearchResultGridView_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["SearchDS"] == null)
Response.Redirect("PESearh.aspx");
DataTable SearchDT = ((DataSet)ViewState["SearchDS"]).Tables[0];
string sortExpression = e.SortExpression;
if (ViewState["SearchSort"] != null && ViewState["SearchSort"].ToString().Length > 0)
{
if (!ViewState["SearchSort"].ToString().Contains(sortExpression))
GridViewSortDirection = SortDirection.Descending;
}
else
{
GridViewSortDirection = SortDirection.Descending;
}
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
sortExpression += " DESC";
SearchDT.DefaultView.Sort = sortExpression;
}
else
{
GridViewSortDirection = SortDirection.Ascending;
sortExpression += " ASC";
SearchDT.DefaultView.Sort = sortExpression;
}
ViewState["SearchSort"] = sortExpression;
this.SearchResultGridView.DataSource = SearchDT;
this.SearchResultGridView.DataBind();
}
和我的分页改编
protected void SearchResultGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SearchResultGridView.DataSource = ViewState["SearchDS"];
SearchResultGridView.PageIndex = e.NewPageIndex;
SearchResultGridView.DataBind();
}
我需要帮助,以便之前的排序也可以对下一页进行排序。请帮助谢谢!
注意:我不想在绑定之前对数据进行排序,因为我希望用户先查看数据,然后决定要绑定的内容。
答案 0 :(得分:2)
您似乎在ViewState["SearchSort"]
中保存了排序表达式。当您更改页面索引时,该值仍应保留在ViewState
变量中,因此您可以抓住它并使用以下命令再次设置:
SearchDT.DefaultView.Sort = ViewState["SearchSort"].ToString();
在对数据进行排序之前,可能希望首先得到DataTable
:
DataTable SearchDT = ((DataSet)ViewState["SearchDS"]).Tables[0];
然后,您可以直接使用新ViewState["SearchDS"]
来代替DataSource
GridView
DataTable
,而不是SearchResultGridView.DataSource = SearchDT;
:
protected void SearchResultGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
DataTable SearchDT = ((DataSet)ViewState["SearchDS"]).Tables[0];
SearchDT.DefaultView.Sort = ViewState["SearchSort"].ToString();
SearchResultGridView.DataSource = SearchDT;
SearchResultGridView.PageIndex = e.NewPageIndex;
SearchResultGridView.DataBind();
}
在一起,你有这样的事情:
ViewState["SearchSort"]
为了安全起见,您可能需要检查以确定{{1}}在分配之前是否存在(如果没有,那么您可以给它一个默认值)。