Indranil.Bharambe Indranil.Bharambe - 5 months ago 12
Javascript Question

Populating Gridview Using Ajax

i have two gridview. on click of one row of one grid i have to populate another gridview. so onClientclick javascript function i called ajax which returns datatable for populating another grid. Now i am stuck how to bind grid view using javascript.

here is code

<asp:gridview id="gridview1"> .....</asp:gridview>
<asp:gridview id="gridview2"> .....</asp:gridview>


codebehind

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton db = (LinkButton)e.Row.Cells[0].Controls[0];

db.OnClientClick = "FunPopulateSecondGrid(" + CType(CType(e.Row.DataItem, System.Data.DataRowView).Row, Label).text + ");"
}
}


javascript

function FunPopulateSecondGrid(productid)
{
$.ajax({
url : '...',
data : { getExEmpList: true, SelectedShop : selectedShop, ajaxCall : true },
method : 'GET',
dataType : 'json',
contentType: "application/json; charset=utf-8",
success : function(data) {
// i am stuck here how to bind it
//gridview2.datasource= data
//gridview2.databind()
},
error : function(xhr, status) {
alert('Sorry, there was a problem while placing your ajax request. Contact Admin!');
}
});
}

Answer

You need to append the data to gridview in success section like this

If you have gridview with Id "gridview2"

function FunPopulateSecondGrid(productid)
    {
       $.ajax({
                url : '...',
                data : { getExEmpList: true, SelectedShop : selectedShop, ajaxCall : true },
                method : 'GET',
                dataType : 'json',
                contentType: "application/json; charset=utf-8",
                 success: function (data) { //you need to append the data to gridview
             for (var i = 0; i < data.d.length; i++) {
                    $("#gridview2").append("<tr><td>" + data.d[i].ProductName + 
                                                "</td><td>" + data.d[i].Price + "</td></tr>");
                 },
                error : function(xhr, status) {
                    alert('Sorry, there was a problem while placing your ajax request. Contact Admin!');
                }
            });
    }

Please find complete solution here :Bind GridView with Jquery