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 do the binding job. The GridView will function normally but there won’t be any page PostBack during the binding process & pagination.
In this application I am using two ASP.NET pages – first one is where this GridView will be shown while the second page is where the GridView actually resides.
Add a new ASP.NET web form on your website and call it gridViewPage.aspx. On 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 codes:
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 I can filter out the products.
The variable called pageNo is 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;
Create a new ASP.NET web form and name it ajax.aspx. In this web form there are 2 main controls –
This page will also contains a div into which I will show the GridView from the second page which is gridViewPage.aspx.
I have also kept a loading image which will be shown during the AJAX calls.
So add the below code to this web form:
<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 called bindButton will trigger the AJAX request and the div called gridViewDiv will show the GridView from the second page.
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 – On the button click event I am calling the BindGridView(1) function. I am passing 1 as it’s parameter which is the Page number. 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 GridView from gridViewPage.aspx. 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 it’s data parameters.
The C# function called Bind() on the gridViewPage.aspx page, will receive these values and then fetch the database records and bind the GridView based on them.
Explanation of – $(“#gridViewDiv”).on(“click”, “.gridViewFooter td a”, function () { //code})
In the above code I have created click events on every anchor tags located under the HTML of GridView’s paging section (i.e. under the class gridViewFooter where the paging links are created).
Then I extract the Page number from the anchor tags and passed this page number to the jQuery Load method.
To understand this you have to see the DOM structure of GridView.
If you inspect the GridView’s HTML from the 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 nunber (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 number and passing this value to the BindGridView() function.
The BindGridView() function then makes the AJAX request and binds it with the records of that page number which I just have extracted. And so in this way the paging links works here.
Look for the download code link below: