Reputation: 2760
//Sort User Table
private void SortGridView(string sortExpression, string direction)
{
DataTable dataTable = BindGridView(Session["useremail"].ToString()).Tables[0];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = sortExpression + direction;
UserTable.DataSource = dataView;
UserTable.DataBind();
}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, " ASC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, " DESC");
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
When I Edit a user and update the edit or do some search, and clear the search the page loads and the sort is lost,
private DataSet BindGridView(string email)
{
.......
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
.....
BindGridView(Session["useremail"].ToString());
}
everytime the page loads or some postback is done the sort is lost how to retain the sort.
Page load
if (PermissionList.Any(item => item.Equals("Edit user")))
{
if (!IsPostBack)
{
BindGridView(Session["useremail"].ToString());
}
}
Upvotes: 0
Views: 1695
Reputation: 26177
Whenever you perform a new sort on your gridview, store the sort expression in a hidden label, or field, and anytime you re-load/bind your gridview, use your saved sort expression to re-sort the table.
.aspx
<asp:Label id="lblHidSortExp" runat="server" visible="false"></asp:Label>
.aspx.cs
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = lblHidSortExp.Text;
if(sortExpression == e.SortExpression)
sortExpression += " DESC";
else
sortExpression == e.SortExpression;
//not sure if this is exactly how you get your datatable, but you get the idea
DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
myView.Sort = sortExpression;
marksGridView.DataSource = myView;
marksGridView.DataBind();
//save sort state
lblHidSortExp.Text = sortExpression;
}
So say in your update function, use your saved sort exp
protected void btnUpdate_Click(object sender, EventArgs e)
{
.....//do update in db
//reload your table in dataview
DataView myView = new DataView(/*load table*/);
//do sort
myView.Sort = lblHidSortExp.Text;
//bind gridview
marksGridView.DataSource = myView;
marksGridView.DataBind();
}
Upvotes: 1
Reputation: 5294
I had a similar problem, the way I aproached this was to save the sort values in the session, then just reset them in Page_load after they are lost.
Upvotes: 0