0

大家好,我的gridview排序有问题。假设我的gridview 有10 行数据和2 列,名称和年龄。分页设置为每页 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();
    }

我需要帮助,以便先前的排序也对下一页进行排序。请帮忙谢谢!

注意:我不想在绑定之前对数据进行排序,因为我希望用户先看到数据,然后再决定绑定什么。

4

1 回答 1

2

您似乎将排序表达式保存在ViewState["SearchSort"]. 当您更改页面索引时,该值仍应保留在ViewState变量中,因此您可以抓住它并再次设置它:

SearchDT.DefaultView.Sort = ViewState["SearchSort"].ToString();

不过,在对数据进行排序之前,可能希望得到第DataTable一个,如下所示:

DataTable SearchDT = ((DataSet)ViewState["SearchDS"]).Tables[0];

ViewState["SearchDS"]然后,您可以使用 new 而不是直接分配DataSourceof your :GridViewDataTable

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"]在分配之前先检查可能是否存在(如果不存在,则可以给它一个默认值)。

于 2012-08-08T03:34:32.063 回答