views:

6418

answers:

2

I'm trying to get a gridview to sort and page manually with no success.

The problem is that when a user clicks the column they want to sort, it sorts that page, but doesn't sort the datasource (dataview) behind the gridview. So when they progress to a different page, their sort is lost. Pretty much I'm looking for a sort that will actually sort the datasource behind the gridview. Here is what I have so far:

protected void GridView_OnSort(object sender, GridViewSortEventArgs e)
 {
  String sortExpression = e.SortExpression;

  if (GridViewSortDirection == SortDirection.Ascending)
  {
   DataView myDataView = new DataView(mybll.GetItemsOrdered());
   myDataView.Sort = sortExpression + " DESC";
   GridView.DataSource = myDataView;
   GridView.DataBind();
  }
  else
  {
   DataView myDataView = new DataView(mybll.GetItemsOrdered());
   myDataView.Sort = sortExpression + " ASC";
   GridView.DataSource = myDataView;
   GridView.DataBind();
  }
 }

Any help would be appreciated. Thanks.

+5  A: 

Save your sorting order in a ViewState.

private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";

public SortDirection GridViewSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null)
            ViewState["sortDirection"] = SortDirection.Ascending;

        return (SortDirection) ViewState["sortDirection"];                
    }
    set { ViewState["sortDirection"] = value; } 
}

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

    if (GridViewSortDirection == SortDirection.Ascending)
    {
        GridViewSortDirection = SortDirection.Descending;
        SortGridView(sortExpression, DESCENDING);
    }
    else
    {
        GridViewSortDirection = SortDirection.Ascending;
        SortGridView(sortExpression, ASCENDING); 
    }   

}

private void SortGridView(string sortExpression,string direction)
{
    //  You can cache the DataTable for improving performance
    DataTable dt = GetData().Tables[0]; 

    DataView dv = new DataView(dt); 
    dv.Sort = sortExpression + direction;         

    GridView1.DataSource = dv;
    GridView1.DataBind();         
}

Why you don't want to use existing sorting functionality? You can always customize it.

Sorting Data in a GridView Web Server Control at MSDN

Here is an example with customization:

http://www.netomatix.com/development/GridViewSorting.aspx

Koistya Navin
Because there are items in the table that I do not want shown in the Gridview, so I omit them before passing the table to the datasource...And I have tried that but it sorts it by the initial column when loading, but the following pages, keep that sorting, but just are sorted by the new column
dangerisgo
A: 

Hi,

i have found a great article presenting complete insight of this phinomenon.

Implement sorting in paging enabled GridView without using DataSources

thanx

awais