sorting a gridview in class
ok i have a project which has many gridview in its pages... now i am sorting the fridveiw using the sorting functio开发者_如何学Gon like this:
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;
}
but this code is being repeated in many pages so i tried to put this function in a C# class and try to call it but i get errors....
for starters i get the viewstate error saying :|
"viewstate does not exist in the current context"
so how do i go about doing this ....??
thanks
so this is what is there in my class:
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;
}
and i am calling it from my code like this:
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();
}
}
and i get view state error...
is here a way to put this entire thing in the class... because it is getting repeated everywhere...
You will need to pass the ViewState in, as the ViewState object is a member of the Page class. Once you moved the code into a separate class, it no longer had access to the ViewState object.
public string GetSortDirection(string column, StateBag viewState) {
// Your code here.
}
精彩评论