asp.net gridview中的分页和排序问题

时间:2012-01-09 16:00:05

标签: c# asp.net sorting gridview paging

我有一个网格视图,我正在实现分页和排序。当我对表格进行排序并选择第2页时,排序将丢失,并且第二个20条记录将在desc中显示,如gridview绑定中所述

private DataSet BindGridView(string field)
        {
         DataSet ds = new DataSet()
      string userQuery = "Select tbl_User.UserID, tbl_User.FirstName from tbl_user order by tbl_user.UserID desc";
      UserTable.DataBind();
            return ds;
        }



<asp:GridView ID="UserTable" runat="server"   PageSize="20" AllowPaging="True"
                    SelectedIndex="0" DataKeyNames="UserID"  OnRowDataBound="UserTable_RowDataBound"                   
   AutoGenerateColumns="false" OnPageIndexChanging="gridView_PageIndexChanging"  AllowSorting="true" OnSorting="gridView_Sorting">

如何保留排序并执行分页,我将排序状态存储在会话中,如何使用它来执行分页。

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            UserTable.PageIndex = e.NewPageIndex;        
            UserTable.DataBind();
            DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
        }

     protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = null;
            if ((Session["UsersortExpression"] == null))
            {
                sortExpression = null;
            }
            else
            {
                sortExpression = (Session["UsersortExpression"].ToString());
            }
            if (sortExpression == e.SortExpression)
            {
                sortExpression += " DESC";
            }
            else
            {
                sortExpression = e.SortExpression;
            }
            DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
            myView.Sort = sortExpression;
            UserTable.DataSource = myView;
            UserTable.DataBind();
            //save sort state 
            Session.Add("UsersortExpression", sortExpression);
        }

2 个答案:

答案 0 :(得分:2)

您可以使用ViewState String vars对源查询应用排序,以存储排序字段并排序方向

确保使用默认值设置ViewState变量:

ViewState["sortDir"] = "DESC"; 
ViewState["sortField"] = "tbl_user.UserID";

然后,修改您的查询字符串:

string userQuery = 
"Select tbl_User.UserID, tbl_User.FirstName " +
"from tbl_user " + 
"ORDER BY " + (String)ViewState["sortField"] + " " + (String)ViewState["sortDir"];

包含在OnSorting中:

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
    // Set new sort direction and sort field
    if ((String)ViewState["sortDir"] == "DESC"){ViewState["sortDir"] = "ASC";}
    else { ViewState["sortDir"] = "DESC"; }
    ViewState["sortField"] = e.SortExpression;

    // Rebind
    ...     
}

这样,您的源数据就会被预先排序,您无需担心使用myView.Sort或遇到任何分页/排序冲突。

答案 1 :(得分:0)

请参阅此article,了解asp.net gridview中的分页和排序。

希望有所帮助。