I have an ASP .NET page with several GridView controls for which I'm implementing sorting and paging.
I'm using session variables to maintain a DataTable representing a given page of the GridView data in the ViewState like so:
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
// Session["Page"] represents the active page of the GridView
// when the Sorting event fires.
DataTable dt = Session["Page"] as DataTable;
if (dt != null)
{
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = "DESC";
}
string ViewState_SortDirection = ViewState["SortDirection"].ToString();
for (int i = 0; i <= ((GridView)sender).Columns.Count - 1; i++)
{
if (e.SortExpression == ((GridView)sender).Columns[i].SortExpression)
{
if (ViewState["SortDirection"].ToString() == "ASC")
{
e.SortDirection = SortDirection.Descending;
((GridView)sender).Columns[i].HeaderText = ((GridView)sender).Columns[i].HeaderText + " ▼";
ViewState["SortDirection"] = "DESC";
}
else if (ViewState["SortDirection"].ToString() == "DESC")
{
e.SortDirection = SortDirection.Ascending;
((GridView)sender).Columns[i].HeaderText = ((GridView)sender).Columns[i].HeaderText + " ▲";
ViewState["SortDirection"] = "ASC";
}
}
}
DataView dv = new DataView(dt)
{
Sort = e.SortExpression + " " + ViewState["SortDirection"]
};
gv.DataSource = dv;
gv.DataBind();
Session["Page"] = dv.ToTable();
DataTable dt = Session["Page"] as DataTable;
}
}
I'd like to have each GridView use the same Sorting event handler. When session variables in the state bag like Session["Page"] are in use, is this session variable specific to the GridView whose Sorting event fires? Or can it be modified by other GridView controls using it to sort on the same page? Meaning, if I have another GridView which also uses Session["Page"] for paging, will that session variable be in that control's scope?
Or, should I just follow the lead of this post's answer and pass only the SortDirection for each session?