Search code examples
c#asp.netsortinggridviewsortdirection

Sorting Gridview Issue


I have a gridview and i am using paging in it

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   GridView1.PageIndex = e.NewPageIndex;
   this.BindData();
}

Now the problem is that when I click on a header to sort the gridview and then I go to the second page, then come back to the first one, it is not remembering the sort expression DESC or ASC.

How can i persist the direction in which it is being sorted no matter on the page index i click on?

thank you


Solution

  • Use ViewState to store the SortDirection like here or here.

    If your BindData method also loads the DataSource what it should, you need to sort your datasource by this SortDirection. Change BindData so that it takes the SortDirection and PageIndex as parameters.

    For example:

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
       this.BindData(this.SortDirection,e.NewPageIndex); //if SortDirection is a property that returns the ViewState value
    }
    

    Then sort the Grid's DataSource and set it's PageIndex there accordingly.