Wednesday, January 20, 2010

ASP.NET Gridview Paging and Sorting with AJAX

To enable paging and sorting of our gridviews with ajax, we must first include the prerequisites of any ajax-enabled asp.net website, the script manager and the update panel.

We place the scriptmanager inside of our form (note the enable partial rendering attribute, it must be set to "true" to enable asynchronous postbacks):

<asp:ScriptManager ID="sm" runat="server" EnablePartialRendering="true" />

Then enclose our gridview with the update panel.

<asp:UpdatePanel ID="up" runat="server">
    <ContentTemplate>
        <asp:GridView ID="gv" runat="server"
        AllowSorting="true" AllowPaging="true" PageSize="10"
        OnSorting="gv_Sorting" OnPageIndexChanging="gv_PageIndexChanging">
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

Notice we set both AllowSorting and AllowPaging to true, then add PageSize for the number of items to be shown per page. Next we'll add the code behind for the sorting and paging events.



Let's start first with the sorting part.

We'll assume in this next snippet that we're getting our data from the database or whatsoever then assign it to a DataSet, then finally bind the dataset to our GridView.

private void BindGridView()
{
    //Get data from there..
    //Assign to dataset here..
    DataSet ds = TheData;

    //Bind dataset to gridview
    gv.DataSource = ds;
    gv.DataBind();

    //We persist DataTable from our DataSet through session.
    Session["sess_table"] = ds.Tables[0];
}

To explain the code above, this function can be placed anywhere in your code behind, it's where you load data into your gridview (*note: imagine TheData already has our data from the database or any other source, loading data to a dataset will be in another lesson). What's new here is the assigning of the DataTable from our DataSet through session. We need that to preserve our data asynchronously.


Then the next step will be to add this other function, again it can be placed anywhere in the code behind.


private string GetSortDirection(string column)
{
    //By default, set the sort direction to ascending.
    string sortDirection = "ASC";

    //Retrieve the last column that was sorted.
    string sortExpression = ViewState["SortExpression"] as string;

    if (sortExpression != null)
    {
        //Check if the same column is being sorted.
        //Otherwise, the default value can be returned.
        if (sortExpression == column)
        {
            string lastDirection = ViewState["SortDirection"] as string;
            if ((lastDirection != null) && (lastDirection == "ASC"))
            {
                sortDirection = "DESC";
            }
        }
    }

    //Save new values in ViewState.
    ViewState["SortDirection"] = sortDirection;
    ViewState["SortExpression"] = column;

    return sortDirection;
}

The code above was taken directly from the msdn website, what it does is just return Ascending or Descending depending on the gridview column header that was clicked.

And finally the sorting event handler..

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
    //Retrieve the DataTable from the session object.
    DataTable dt = Session["sess_table"] as DataTable;

    if (dt != null)
    {
        //Sort the table.
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        //Bind the sorted table to the gridview.
        gv.DataSource = Session["sess_table"];
        gv.DataBind();
        //Update the UpdatePanel or the changes won't show.
        up.Update();
    }
}




Okay we're already halfway there, next is the paging part, this is really short and simple compared to the sorting one.

protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gv.PageIndex = e.NewPageIndex;
    BindGridView();
    upTransactions.Update();
}

3 lines and that's it. Okay to explain: the first line just sets the new page index to the gridview's PageIndex attribute. Next we use the function we created earlier to bind our data to the gridview again (that's assuming the imaginary code, remember?). And then finally update our UpdatePanel to reflect the changes.

...And thanks, I hope you learned something from this post, or remembered something you forgot.

-k

4 comments:

  1. you need to edit your code a little, you have to set the updatemode to conditional of the update panel for up.update() to work....by the way, great post man, really helped me out...

    ReplyDelete
  2. Spent the last 4 days trying to figure out how to do this and finally stumbled across this page. This was a huge help! Thanks!!!

    ReplyDelete