Dynamically append data to the grid in ASP.NET with jQuery

Sheonarayan
Posted by in ASP.NET category on for Advance level | Points: 250 | Views : 157228 red flag

In this article, we shall learn how to dynamically append data to the Grid using ASP.NET and jQuery.
Recommendation
Read Loading CSS class names in C# before this article.

Introduction

This post is written in support of this forum thread where the author is asking how to append data in the grid that is found from the database based on id.

To achieve this, we shall use jQuery for front end and ASP.NET with SQL Server as backend.

Use of jQuery

First refer the jQuery file under the <head></head> element of the page as it is shown below.

<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.1.4.js"></script>
</head>

Form with the Grid

Now create a form with the Grid that will enable us to find the record based on the id value and list the data. In below code snippet, we have a Text box and a button. On click of the button, we are calling GetData() javascript function. Next, we have a html table with the header of the data hard coded as "<th></th>". The data to be added dynamically has to be appended in the <tbody> whose id is "result".

<form id="form1" runat="server">
    <p>
        Enter ID: <input type="number" id="id" required /> 
        <input type="button" onclick="GetData()" value="Get" />
    </p>
    <div>
        <table>
            <tr>
                <th>First name</th><th>Last name</th><th>Age</th>
            </tr>
            <tbody id="result">

            </tbody>
        </table>
    </div>
    <script>
        function GetData() {
            var thisId = $("#id").val();
            $.get("GetData.aspx", { id: thisId }, function (data) {
                $("#result").append(data);
            });
        }
    </script>
    </form>
When user writes the Auto Id value in the Textbox and clicks button, the GetData() function of the <script> block executes. In this function, we are using $.get ajax function that partially sends request to "GetData.aspx" page with "id" as parameter whose value is nothing but the value of the text box. Once the response form the server is received, the data is appended to the element whose id is "result".

Screen shot of the page

Retrieving data from database

Now create a GetData.aspx page and remove all codes of .aspx page apart form <%@ Page directive. In the code behind page (GetData.aspx.cs), write below code.

Extra namespace to be used

using System.Text;
using System.Data;
using System.Data.SqlClient;

As the request to this page is coming with jQuery.get function, so retrieval of "id" value being send from $.get is retrieved using Request.QueryString. So in the Page_Load method, we are checking for its value and calling SendData() method by passing the id value sent to this page.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
        {
            SendData(int.Parse(Request.QueryString["id"]));
        }
    }

    private void SendData(int id)
    {
        string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        DataTable table = new DataTable();
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            string sql = "SELECT * FROM PersonalDetails WHERE AutoID = @autoId";
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.AddWithValue("@autoId", id);
                using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                {
                    ad.Fill(table);
                }
            }            
        }
        StringBuilder strB = new StringBuilder();
        foreach(DataRow row in table.Rows)
        {
            strB.Append("<tr><td>" + row["FirstName"] + "</td><td>" + row["LastName"] + "</td><td>" + row["Age"] + "</td></tr>");
        }
        
        Response.Write(strB.ToString());
    }
In the SendData() function, we are using ADO.NET to retrieve the data from the database based on id and forming a string (html table row) using StringBuilder and the same is being returned using Response.Write method. 

This will add the found record from the database in the Grid (<table>).

Hope this article will be helpful. Thanks for reading.

Keep reading and sharing your knowledge to others.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)