GridView is a powerful control in ASP.NET. It can can be used to show the data in grid format (rows and columns). Typically, when we bind a GridView with the data, then there is page reloading. This page reload can sometimes be frustrating to the users, so as a developer, you may think of removing this page reloading when binding the GridView.
Avoid Update Panel & Update Progress
The first thought which comes to your mind is to use ASP.NET AJAX controls. These are the Update Panel and Update Progress. Although they are simple to use, I recommend you not to use them in your Websites.
I say this because they
- They make your page heavy by including too many unnecessary scripts.
- Slows down your page.
- Breakpoints may stop working in Visual Studio during the code debugging.
- May give you new headaches due to the problems that can arise due to them. Some problems are listed below.
- Some button clicks may not in your page.
- AJAX is not working properly.
- Other features of the page stops working at all.
I myself have noticed such problems in the page and these gave me too many headaches. Thus, I decided not to use them any further. Hence, you should not use Update Panel & Update Progress in your Website.
Use jQuery instead of Update Panel & Update Progress
You can just avoid these AJAX controls and instead use jQuery to do all sorts of AJAX works. The jQuery is just a JavaScript library, which is very easy to lean, and makes code execution fast. Moreover, it does not make your page heavy and slow.
Therefore, let us use jQuery to make AJAX calls and let me prove my point.
Bind GridView with no page reload
Let us see how to bind a GridView in such a way that there is no page reload. We will just use an AJAX method from jQuery to do this work. This method name is jQuery Load, which can be used to load the text, XML, JSON, HTML etc. from the external files.
Here, we will use 2 pages – first is a “ASP.NET page”, which contains the GridView while the second is HTML page from where the AJAX calls will be made.
The code of ASP.NET page
Name the page “result.aspx” or any name you want. In this page, we have a GridView control and we bind this control from the database values.
For the purpose of this tutorial, I have taken “Northwind” database and I am fetching the values from “Products” table.
In my SQL query, I am applying the “Where” clause to filter the products by ProductName and this ProductName, which I am getting through “Request.Form["productName"]” in my page.
The C# code of the page is given below,
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- BindGridView();
- }
-
- void BindGridView()
- {
- string productName = Request.Form["productName"];
- 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.DataBind();
- }
- catch (Exception ex)
- {
- Response.Write(ex.Message);
- }
- finally
- {
- }
- }
The .ASPX page code is given below.
- <asp:GridView ID="gridView" runat="server">
- <Columns>
- <asp:TemplateField HeaderText="Serial No">
- <ItemTemplate>
- <%#Container.DataItemIndex+1 %>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
The code of the HTML page
In HTML page, we will bind GridView of ASP.NET page and show that GridView is here in HTML page. In HTML page, we have the controls given below..
- Select
It contains the product names. They will used to filter the database values and we use them in the where clause of the SQL query (see the query given in ASP.NET code).
- Button
The button click will call the jQuery load method. The load method will cause the GridView of the ASP.NET page to bind with the database values.
- Div
Div is used to show the GridView of ASP.NET page.
- Image
It is a loading .GIF image that will be shown during AJAX calls.
HTML code of the page is given below.
- <div class="container">
- <div id="content">
- <h3>Bind GridView using jQuery Load</h3>
- <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>
- </div>
- </div>
To style HTML controls, add CSS to the Page Head section.
- <style>
- .container {
- width: 960px;
- margin: auto;
- color: #FFF;
- font-size: 25px;
- }
-
- .container h3 {
- font-size: 25px;
- text-decoration: underline;
- text-align: left;
- }
-
- .container #content {
- border: dashed 2px #CCC;
- padding: 10px;
- }
-
- .container #content #gridViewDiv {
- padding-top: 20px;
- }
-
- .container #content #gridViewDiv {
- margin-top: 20px;
- }
-
- .container #content #gridViewDiv tr:nth-child(1) {
- background: #0184e3;
- }
-
- .container #content .imageDiv {
- text-align: center;
- }
-
- .container #content .imageDiv img {
- display: none;
- }
- </style>
To start up with jQuery, first include its reference in your HTML page, as shown below.
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
Note
Put this reference just before the ending body tag of your page.
Now, add the jQuery code given below after jQuery reference.
- <script>
- $(document).ready(function () {
- $("#bindButton").click(function (e) {
- $("#gridViewDiv").load("result.aspx #gridView", { "productName": "" + $("#productSelect").val() + "" }, 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
We place jQuery code inside the “$(document).ready(function () { //code });” block. Inside this, we have created the button click event for the button with Id “bindButton”.
In this button click event, we are calling the jQuery Load method to do the AJAX call. It calls ASP.NET page and loads the GridView by providing GridView’s Id “#gridView”.
It is also passing the value of the select to ASP.NET page and shows the GridView inside the div with an Id “gridViewDiv”.
In general, the syntax of jQuery load method is given below.
- $("Div Id where GridView will be shown").load("asp.net page #gridView id", { "value to send": "value of the select" }, function (response, status, xhr) {
-
- });
- });
The ajaxStart() event is called, when the AJAX request starts. In this event, we had shown the loading .GIF image. Similarly, the ajaxStop() event is called, when the AJAX request finishes. In this event, we hide the loading image.
How it all works
We have written the full jQuery Load code. Now, it’s time to check how it works. The user can select a value from the select control and click the button. On clicking the button, jQuery load calls ASP.NET page, binds it with the database values and shows the GridView inside a div.
Everything is done with no page reload, as the work is done with AJAX, using jQuery.
Conclusion
I hope, you enjoyed this tutorial and can now understand that it is very easy to make AJAX features with jQuery. Please share this on Facebook, Twitter and your other social accounts, so that your friends can also know about this tutorial.