Thursday, August 15, 2013

2 Ways to bind data to gridview using client side code with asp.net c# jquery

2 Ways to bind data to gridview using client side code
In this article,I would like to explain "How to bind data to Gridview using Client Side Code in 2 ways with asp.net, c#, jquery".In my previous sections, i have already shared articles related to Gridview, Different binding techniques.


Here I am going to explain in simple way to bind data to gridview using client side in order to increase the performance of the application.

Please follow the steps: 

Here we need to create two sections, One is Server side and another one client side. 

Lets start with server side. 
First, Select New aspx form and change the name as ServerSide.aspx. 
Next, Write the following code in serverside.cs file 

Add the following namespaces
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

Next, Add the following two Web methods for two methods
[WebMethod]
    public static string GetStateInfo1()
    {
        string query = "select Stateid,StateName,StateCode from STATE";
        string strConnString = ConfigurationManager.ConnectionStrings["dbConnection"].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();
                    }
                }
            }
        }
    }

[WebMethod]
    public static StateDetails[] GetStateInfo2()
    {
        DataTable dt = new DataTable();
        List details = new List();
        string strConnString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand("select Stateid,StateName,StateCode from STATE", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    StateDetails st = new StateDetails();
                    st.State_id = dtrow["Stateid"].ToString();
                    st.StateName = dtrow["StateName"].ToString();
                    st.StateCode = dtrow["StateCode"].ToString();
                    details.Add(st);
                }
            }
        }
        return details.ToArray();
    }
    public class StateDetails
    {
        public string State_id { get; set; }
        public string StateName { get; set; }
        public string StateCode { get; set; }
    }

Next,Select New aspx form and change the name as Clientside.aspx 
Next,Open the aspx form and add two buttons and one Gridview. 
Next,Change the button names as Method1 and Method2 and Gridview name as gvStates. 
Next,Write the two different scripts for two methods 

Method 1:
  $("#btnMethod1").click(function () {
                $.ajax({
                    type: "POST",
                    url: "ServerSide.aspx/GetStateInfo1",
                    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*=gvStates] tr:last-child").clone(true);
                //remove the lst row created by binding the dummy row from code behind on page load
                $("[id*=gvStates] tr").not($("[id*=gvStates] tr:first-child")).remove();
                var count = 1;
                $.each(users, function () {
                    //var users = $(this);
                    $("td", row).eq(0).html($(this).find("Stateid").text());
                    $("td", row).eq(1).html($(this).find("StateName").text());
                    $("td", row).eq(2).html($(this).find("StateCode").text());
                    $("[id*=gvStates]").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*=gvStates] tr:last-child").clone(true);
                });
            }

Method 2:
 $("#btnMethod2").click(function () {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "ServerSide.aspx/GetStateInfo2",
                    data: "{}",
                    dataType: "json",
                    success: function (data) {
                        for (var i = 0; i < data.d.length; i++) {
                            $("#gvStates").append("" + data.d[i].Stateid + "
" + data.d[i].StateName + "
" + data.d[i].StateCode + "
"); } }, error: function (result) { alert("Error"); } }); });
Next, Add this script file and this following line before the script


 $(document).ready(function () {
});

That's it.Please let me know if you have any queries.

Labels: , , , , ,

1 Comments:

At September 24, 2013 at 11:16 AM , Blogger Developers Code said...

Thankyou Wilder Tarazona..

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home