sorting and paging with gridview asp.net

dangerisgo picture dangerisgo · Mar 31, 2009 · Viewed 152k times · Source

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.

Answer

Konstantin Tarkus picture Konstantin Tarkus · Mar 31, 2009

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