0

I have an issue with my sorting when navigating between pages. When I go to a new page, the sorting order is lost and the user has to sort again.

I have ran through my code and know the issue lies in PageIndexChanging event of the gridview. Where am rebind the gridview with fresh data.

However, I am not sure how to avoid this? How do I store the sort order when rebinding the gridview? ViewState perhaps?

Any suggestions please?

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    PopulateProductClass();
    PopulateProduct();
    PopulateOrderList();  
  }          
}

private void PopulateOrderList()
{
  DateTime d;
  DateTime d2;

  CustomerInfo ki = CustomerInfoProvider.GetCustomerInfoByUserID(CooneenHelper.GetUserImpersonisationID());
  int nKustomerID = ki.CustomerID;
  DataTable dts = new DataTable();
  dts.Columns.Add("OrderDate", typeof(DateTime));
  dts.Columns.Add("OrderNumber", typeof(string));
  dts.Columns.Add("OrderItemSKUName", typeof(string));
  dts.Columns.Add("SKUNumber", typeof(string));
  dts.Columns.Add("OrderItemStatus", typeof(string));
  dts.Columns.Add("OrderItemUnitCount", typeof(string));
  dts.Columns.Add("mtrx_Code2", typeof(string));

  QueryDataParameters qdp = new QueryDataParameters();
  qdp.Add("@CustomerID", nKustomerID);

  if (drpProductClass.SelectedValue.ToString() != "0" || drpProductClass.SelectedValue.ToString() == null) { qdp.Add("@OrderItemWRClass", drpProductClass.SelectedItem.ToString()); }
  if (drpProduct.SelectedValue.ToString() != "0") { qdp.Add("@OrderItemSKUID", drpProduct.SelectedValue.ToString()); }                
  if (txtStartDate.Text != "") { d = DateTime.Parse(txtStartDate.Text); qdp.Add("@OrderItemDateFrom", d.ToString("yyyy-MM-dd")); }
  if (txtEndDate.Text != "") { d2 = DateTime.Parse(txtEndDate.Text); qdp.Add("@OrderItemDateTo", d2.ToString("yyyy-MM-dd")); }

  DataSet ds = gc.ExecuteQuery("CN_GetOrderItemByCustID", qdp, QueryTypeEnum.StoredProcedure, true);
  foreach (DataRow dr in ds.Tables[0].Rows)
  {
    DataRow drNew = dts.NewRow();
    drNew["OrderDate"] = ValidationHelper.GetDateTime(dr["OrderDate"], DateTime.Now).ToShortDateString();
    drNew["OrderNumber"] = dr["OrderNumber"].ToString();
    drNew["OrderItemSKUName"] = dr["OrderItemSKUName"].ToString();
    drNew["SKUNumber"] = dr["SKUNumber"].ToString();
    drNew["OrderItemStatus"] = dr["OrderItemStatus"].ToString();
    drNew["OrderItemUnitCount"] = dr["OrderItemUnitCount"].ToString();
    drNew["mtrx_Code2"] = dr["mtrx_Code2"].ToString();
    dts.Rows.Add(drNew);
  }
  //Clear the TextBox
  litResults.Text = String.Empty;
  if (dts.Rows.Count == 1)
    litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";
  else
    litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";      
  try
  {
    Session["Data"] = dts;
  }
  catch(Exception ex)
  {
    throw ex;
  }
  gvOrderItems.Visible = true;
  gvOrderItems.DataSource = dts.DefaultView;      
  gvOrderItems.DataBind();      
  if (dts.Rows.Count > 1) litResults.Text += " - Showing page " + (gvOrderItems.PageIndex + 1).ToString() + " of " + gvOrderItems.PageCount.ToString();
}

private string SortCriteria
{
  get
  {
    if (ViewState["sortCriteria"] == null)
    {
      ViewState["sortCriteria"] = "";
    }

    return ViewState["sortCriteria"].ToString();
  }
  set
  {
    ViewState["sortCriteria"] = value;
  }
}

public SortDirection SortDirection
{
  get
  {
    if (ViewState["SortDirection"] == null)
    {
      ViewState["SortDirection"] = SortDirection.Ascending;          
    }
    return (SortDirection)ViewState["SortDirection"];
  }
  set
  {
    ViewState["SortDirection"] = value;
  } 
}

protected void gvOrderItems_Sorting(object sender, GridViewSortEventArgs e)
{
  string sortExpression = e.SortExpression;
  string direction = string.Empty;

  DataTable dt = (DataTable)Session["Data"];

  if (dt.Rows.Count > 0)
  {        
    DataView dataView = new DataView(dt);

    if (SortDirection == SortDirection.Ascending)
    {
      SortDirection = SortDirection.Descending;         
      direction = " DESC";
    }
    else
    {
      SortDirection = SortDirection.Ascending;
      direction = " ASC";
    }
    dataView.Sort = sortExpression + direction;
    gvOrderItems.DataSource = dataView;
    gvOrderItems.DataBind();        
  }
} 

protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
  gvOrderItems.PageIndex = e.NewPageIndex;
  PopulateOrderList();
}
KJSR
  • 1,679
  • 6
  • 28
  • 51

3 Answers3

0

Maybe you're databinding the GridView on every postback from Page_Load.

You should do that only at the first time. Use the Page.IsPostBack property:

protected void Page_Load(object sender, System.EventArgs e)
{
   if(!Page.IsPostBack)
       // GridBind here
}
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
  • Hi Vignesh I tried that before, however I still lose my sorting when I navigate to next page – KJSR Apr 13 '16 at 09:43
  • 1
    Post your full code. You need to use `ViewState` and check this [solution](http://stackoverflow.com/a/12167332/2118383) @Kevin – Vignesh Kumar A Apr 13 '16 at 09:44
  • Thank you for the link. Gives me some direction, however how do you suggest i should modify the `PopulateOrderList()`? – KJSR Apr 13 '16 at 10:08
  • 1
    @Kevin Yes you need to alter your binding method with sortdirection and data – Vignesh Kumar A Apr 13 '16 at 10:10
  • Thanks Vignesh, I have further updated my code to show the 2 properties I have SortCriteria and SortDirection. How can I reuse them to include them in the binding method? – KJSR Apr 13 '16 at 10:17
0

Resolved my issue thanks to Vignesh on suggesting of using ViewState. However I choose to use a Session variable.

Inside the sorting event handler, after the sorting is carried out I stored the sorted list in a Session Session["SortedView"] = dataView;. Now during the PageIndexChanging1 I check if this session variable is empty and use accordingly.

protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
  gvOrderItems.PageIndex = e.NewPageIndex;
  if (Session["SortedView"] != null)
  {
    gvOrderItems.DataSource = Session["SortedView"];
    gvOrderItems.DataBind();
  }
  else
  {
    PopulateOrderList();
  }      
}
KJSR
  • 1,679
  • 6
  • 28
  • 51
0

In this case, especially in MVC, pass the sort order in query string and add it to the cookie. Retrieve the sort order from cookie when page refreshes and assign the same to current sort order if nothing has been changed. this worked fine when we move to the next page (sort order is retained).

if (Request.Query["sortOrder"].Any())
    {
        sortOrder = Request.Query["sortOrder"];
        // save the sort order in cookie
        Response.Cookies.Append("sortOrder", sortOrder);
    }
    // get the last saved sort order from cookie
    else if (Request.Cookies["sortOrder"] != null)
    {
        sortOrder = Request.Cookies["sortOrder"];
    }