Saturday, June 22, 2013

How To- Bind Data to Gridview using jQuery in ASP.Net

In this post, I am explaining how to bind data to Gridview using jQuery in ASP.Net through Ajax call.

In previous posts, I explained Page Scroll to Top with jQuery, Automatically Refresh Page Using Java Script , How to Create a Textarea Character Counter, Animated Sliding Recent Post Widget For Blogger, Change Input to Upper Case using Java Script, Calculate Age from Date of Birth Using Java Script, jQuery .toggleClass() example and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

ASPX Page

Gridview Markup
<asp:GridView ID="grdDemo" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
    Font-Size="10pt" HeaderStyle-BackColor="GrayText" HeaderStyle-ForeColor="White" Width="500px">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="FName" HeaderText="First Name"/>
        <asp:BoundField DataField="LName" HeaderText="Last Name"/>
        <asp:BoundField DataField="Email" HeaderText="E-mail"/>
    </Columns>
</asp:GridView>

C# Code

Required Namespaces
using System;
using System.Data;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
Web Method for Ajax Call and Bind Dummy Row Method
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDummyRow();
    }
}
/// <summary>
/// Function to bind the dummy row to gridview
/// </summary>
private void BindDummyRow()
{
    DataTable dummy = new DataTable();
    dummy.Columns.Add("ID");
    dummy.Columns.Add("FName");
    dummy.Columns.Add("LName");
    dummy.Columns.Add("Email");
    dummy.Rows.Add();
    grdDemo.DataSource = dummy;
    grdDemo.DataBind();
}
/// <summary>
/// WebMethod to handle the jQuery Ajax call
/// </summary>
/// <returns></returns>
[WebMethod]
public static string GetUserInfoData()
{
    string query = "SELECT * FROM UserInfo";    
    string strConnString = ConfigurationManager.ConnectionStrings["DemoConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    return ds.GetXml();
                }
            }
        }
    }
}
In the above code,I have create a BindDummyRow method which is used in Page _Load method to bind the gridview.
I have also create a WebMethod named GetUserInfoData whic is called by jQuery Ajax to get the data from Database.

Client Side Code

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $.ajax({
            type: "POST",
            url: "BindGridViewusingJQuery.aspx/GetUserInfoData",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert("Failure : " + response.d);
            },
            error: function (response) {
                alert("Error : " + response.d);
            }
        });
    });
 
    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        var users = xml.find("Table");
        //create a new row from the last row of gridview
        var row = $("[id*=grdDemo] tr:last-child").clone(true);
        //remove the lst row created by binding the dummy row from code behind on page load
        $("[id*=grdDemo] tr").not($("[id*=grdDemo] tr:first-child")).remove();
        var count = 1;
        $.each(users, function () {
            //var users = $(this);
            $("td", row).eq(0).html($(this).find("ID").text());
            $("td", row).eq(1).html($(this).find("FName").text());
            $("td", row).eq(2).html($(this).find("LName").text());
            $("td", row).eq(3).html($(this).find("Email").text());
            $("[id*=grdDemo]").append(row);
            //define the background stryle of newly created row         
            if (count == 1 || (count % 2 != 0)) {
                $(row).css("background-color", "#ffffff");
            }
            else {
                $(row).css("background-color", "#D2CDCD");
            }
            count = count + 1;
            row = $("[id*=grdDemo] tr:last-child").clone(true);
        });
    }
</script>
In the above code snippet a jQuery AJAX call is made to the Web method GetUserInfoData in the document ready event of the page. The web method then returns an XML string which is parsed using the jQuery parseXML method. Once the XML document is created rows are created and appended to the ASP.Net Gridview control.

Output Screen
Bind Data to Gridview using jQuery or Json in ASP.Net
I hope this article will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

^ Scroll to Top