好的,我有一个项目,它的页面中有很多 gridview...现在我正在使用这样的排序函数对 fridveiw 进行排序:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["TaskTable2"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = Session["TaskTable2"];
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection2 = "ASC";
// Retrieve the last column that was sorted.
string sortExpression2 = ViewState["SortExpression2"] as string;
if (sortExpression2 != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression2 == column)
{
string lastDirection = ViewState["SortDirection2"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection2 = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection2"] = sortDirection2;
ViewState["SortExpression2"] = column;
return sortDirection2;
}
但这段代码在许多页面中重复出现,所以我试图将此函数放在 C# 类中并尝试调用它,但出现错误....
对于初学者,我收到 View 状态错误:|
“ View 状态在当前上下文中不存在”
那么我该怎么做......?
谢谢
这就是我类的内容:
public string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection2 = "ASC";
// Retrieve the last column that was sorted.
string sortExpression2 = ViewState["SortExpression2"] as string;
if (sortExpression2 != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression2 == column)
{
string lastDirection = ViewState["SortDirection2"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection2 = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection2"] = sortDirection2;
ViewState["SortExpression2"] = column;
return sortDirection2;
}
我是这样从我的代码中调用它的:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["TaskTable2"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + new impersonateClass().GetSortDirection(e.SortExpression);
GridView1.DataSource = Session["TaskTable2"];
GridView1.DataBind();
}
}
我得到 View 状态错误...
这是一种将整个事情放在类里面的方法...因为到处都在重复...
最佳答案
您需要传入 ViewState,因为 ViewState 对象是 Page 类的成员。一旦您将代码移至单独的类中,它就无法再访问 ViewState 对象。
public string GetSortDirection(string column, StateBag viewState) {
// Your code here.
}
关于c# - 在类里面对 gridview 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2434465/