Bind GridView with Paging using jQuery Load with No Page Refresh

Bind GridView with Paging using jQuery Load with No Page Refresh

In this GridView tutorial you will learn how to bind it with AJAX. Here I will not use controls of ASP.NET AJAX toolkit, I will just use jQuery to bind it. The GridView will function like normally but there won’t be any page PostBack during the binding process neither on clicking the paging links.

The Application Setup

In this application I am using two ASP.NET pages – first one where this GridView will be shown while the second page is where the GridView resides.

Creating the GridView and Binding it With Database

Add a new ASP.NET page in your website and name it “gridViewPage.aspx”. Into this page add a GridView control.

<asp:GridView ID="gridView" runat="server" AllowPaging="true" PageSize="7" PagerStyle-CssClass="gridViewFooter">
    <Columns>
        <asp:TemplateField HeaderText="Serial No">
            <ItemTemplate>
                <%#Container.DataItemIndex+1 %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now open its .cs page and add the GridView binding code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Bind();
    }
}

void Bind()
{
    string productName = Request.Form["productName"];
    string pageNo = Request.Form["pageNo"];
    string query = productName == "All" ? "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS" : "SELECT PRODUCTNAME,QUANTITYPERUNIT,UNITPRICE,UNITSINSTOCK FROM PRODUCTS WHERE PRODUCTNAME='" + productName + "'";

    SqlConnection conn = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    DataTable dataTable = new DataTable();
    conn.ConnectionString = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
    cmd.Connection = conn;

    cmd.CommandType = CommandType.Text;
    cmd.CommandText = query;
    cmd.Connection = conn;

    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
    sqlDataAdapter.SelectCommand = cmd;
    try
    {
        sqlDataAdapter.Fill(dataTable);
        gridView.DataSource = dataTable;
        gridView.PageIndex = Convert.ToInt32(pageNo) - 1;
        gridView.DataBind();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
    } 
}

Explanation – I am calling the “Bind()” function in the “!IsPostBack” part of Page Load event. This function fetches the value from the database and binds the GridView with these values.

First I am grabbing the product name value from “Request.Form[“productName”]” and pageNo from “Request.Form[“pageNo”]”. Let me tell you that these values will be send by the AJAX call from the other page. I will explains how these values are sent here in the second page code (where the GridView will be shown).

The “productName” variable will modify the SQL query so that we can filter out the products.

The “pageNo” variable will be used to show the records on the current page of the GridView. For this I am setting the GridView’s pageIndex with this code:

 gridView.PageIndex = Convert.ToInt32(pageNo) - 1;
In the above code I am binding data from the Northwind Database using ADO.NET
Showing the GridView in Another Page

Create a new ASP.NET page and name it “ajax.aspx”. In this page there are 2 main controls –

  • A HTML Select control that contains a set of options. User can select any option.
  • A button which when clicked will bind a GridView. Note that the GridView remains on the second page.

This page will also contains a div into which I will show the GridView from the second page “gridViewPage.aspx”.
I have also kept a loading image which will be shown during the AJAX calls.
Add the below code to this page:

<select id="productSelect">
    <option value="All">All</option>
    <option value="Chai">Chai</option>
    <option value="Chang">Chang</option>
    <option value="Konbu">Konbu</option>
    <option value="Tunnbröd">Tunnbröd</option>
</select>
<button id="bindButton">Click Here</button>
<div class="imageDiv">
    <img src="loading.gif" />
</div>
<div id="gridViewDiv"></div>

The button “bindButton” will trigger the AJAX request and the div “gridViewDiv” will show the GridView from the second page.

You may be thinking how I will show the GridView from another page. The answer is through jQuery Load method, which is an AJAX method and is used to fetch any HTML element from external pages.

For your understanding the jQuery Load method’s syntax and full description is given in this article – jQuery Load.

Next add the below jQuery code to the page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>    
<script>
    $(document).ready(function () {
        $("#bindButton").click(function (e) {
            BindGridView(1);
            return false;
        });

        $("#gridViewDiv").on("click", ".gridViewFooter td a", function () {
            var hrefValue = $(this).attr("href")
            var commaIndex = hrefValue.indexOf(",")
            var pageNo = hrefValue.substring(commaIndex + 2).replace("')", "").replace("Page$", "")
            BindGridView(pageNo)
        });

        function BindGridView(pageNo) {
            $("#gridViewDiv").load("gridViewPage.aspx #gridView", { "productName": $("#productSelect").val(), "pageNo": pageNo }, function (response, status, xhr) {
                if (status == "error")
                    $("#gridViewDiv").html("Error: " + xhr.status + ": " + xhr.statusText);
            });
        }

        $(document).ajaxStart(function () {
            $("img").show();
        });

        $(document).ajaxStop(function () {
            $("img").hide();
        });
    });
</script>

Explanation – In the button click event I am calling the “BindGridView(1)” function. I am passing “1” as its parameter which is the Page no. This is because I want to bind the GridView with the records of the first page.

Now see the “BindGridView()” function where I am using jQuery Load method to fetch the gridViewPage.aspx page’s GridView. I have also placed the GridView’s id (#gridView ) on it.

To the jQuery Load method, I am passing the “productName” (the select value) and “pageNo” (page number whose records the GridView will show), to its data parameters.

The C# function “BindGridView” on the “gridViewPage.aspx” page, will receive these values and then fetch the database records and bind the GridView based on them.

gridview with paging

Explanation of – $(“#gridViewDiv”).on(“click”, “.gridViewFooter td a”, function () { //code})
In this jQuery code I have created click events on every anchor tags located under the GridView’s paging html (i.e. under the class “gridViewFooter” where the paging links are created).

Then I extract the Page no from the anchor tags and pass this page No to the jQuery Load method.

To understand this you have to see the DOM structure of GridView.

GridView Paging DOM Structure

If you inspect the GridView’s Dom on Chrome’s Developer tool (Ctrl+Shift+I) you will see the paging anchors contains a string like “javascript:__doPostBack(‘gridView’,’Page$2′)” on the href tag.

This string contains the page no – here ‘Page$2’ as this is the href tag’s value from the 2nd page’s anchor.
On the click event on these anchor tags I am getting the page no and passing this value to the “BindGridView” function.

The “BindGridView()” function then makes the AJAX request and binds it with the records from the page number. And so in this way the paging links works here.

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.