对GridView进行排序的会话存在问题
本文关键字:会话 存在 问题 排序 GridView | 更新日期: 2023-09-27 17:58:10
我将Session["TaskTable"]
作为GridView的数据源时遇到问题。当我第一次打开.aspx网站时,Session["TaskTable"]
为空,如果我重新加载页面(F5),Session["TaskTable"]
就是我的数据表taskTable
。那怎么可能呢?只有当我第一次重新加载页面时,我才能进行排序。有什么想法吗?感谢
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable taskTable = new DataTable("TaskList");
taskTable = dtCloned;
Session["TaskTable"] = taskTable;
GV_Projekte.DataSource = Session["TaskTable"];
GV_Projekte.DataBind();
}
}
对于我的GridView 的排序
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["TaskTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GV_Projekte.DataSource = Session["TaskTable"];
GV_Projekte.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
这是因为Page.IsPostback条件。当页面没有回发时,它将会话分配给了一个变量,现在这个值将一直存在,直到会话过期为止。
进行以下练习。
protected void Page_Load(object sender, EventArgs e)
{
if (Session["a"]==null)
{
Response.Write("Session is empty");
}
else
{
Response.Write("Session is not empty");
Response.Write(Session["a"].ToString());
}
if (!Page.IsPostBack)
{
Session["a"] = "Jalpesh";
}
}
在空白页中,我正在做和您正在做的相同的事情,但第一次加载页面时,它将打印"会话为空",但在会话到期之前,它不会为空,因此会打印"会话不为空"。
所以,如果您需要会话值null,您必须在某个地方将会话分配给null。
我找到了解决方案,函数gv_Sorting
必须位于page_load
之前,以便第一次正确填充。另请参阅我获得代码的示例:http://msdn.microsoft.com/de-de/library/system.web.ui.webcontrols.gridview.sorting(v=vs.110).aspx