asp.net网格视图中的分页和排序问题
本文关键字:分页 排序 问题 net 网格 视图 asp | 更新日期: 2023-09-27 18:19:59
我有一个网格视图,在其中我实现了分页和排序。当我对表格进行排序并选择第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);
}
您可以使用ViewState String变量对源查询应用排序,以存储排序字段和排序direction:
确保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
或遇到任何分页/排序冲突。