locked
i want to Add, Edit and Delete inside gridview using ajax jquery call in asp.net webform RRS feed

  • Question

  • User-471420332 posted

    I want to add, delete and edit inside gridview  using ajax jquery call.

    Please check the below url for reference same using ajax call

    https://www.aspsnippets.com/Articles/GridView---Add-Edit-Update-Delete-and-Paging-the-AJAX-way.aspx

    Saturday, February 23, 2019 10:13 PM

Answers

  • User-1174608757 posted

    Hi,

    Accordigng to your description, I have made a sample here. I suggest you to use Webservice in code behind to solve  ajax request. Here is the demo , I hope it could help you.

    Mydatatable:

    Aspx:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="../Scripts/jquery-3.3.1.js"></script>
        <script>
             $(function () {
            $.ajax({
                type: "POST",
                url: "ajaxforGridview.aspx/GetCustomers",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: OnSuccess
              });
                 $("body").on("click", "[id*=btnAdd]", function () {
            var txtName = $("[id*=txtName]");
            var txtCountry = $("[id*=txtCountry]");
            $.ajax({
                type: "POST",
                url: "ajaxforGridview.aspx/InsertCustomer",
                data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var row = $("[id*=gvCustomers] tr:last-child").clone(true);
                    AppendRow(row, response.d, txtName.val(), txtCountry.val());
                    txtName.val("");
                    txtCountry.val("");
                }
            });
            return false;
        });
        $("body").on("click", "[id*=gvCustomers] .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    $(this).find("input").show();
                    $(this).find("span").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            row.find(".Delete").hide();
            $(this).hide();
            return false;
                 });
                 $("body").on("click", "[id*=gvCustomers] .Update", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    span.html(input.val());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Cancel").hide();
            $(this).hide();
     
            var customerId = row.find(".CustomerId").find("span").html();
            var name = row.find(".Name").find("span").html();
            var country = row.find(".Country").find("span").html();
            $.ajax({
                type: "POST",
                url: "ajaxforGridview.aspx/UpdateCustomer",
                data: '{customerId: ' + customerId + ', name: "' + name + '", country: "' + country + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
     
            return false;
        });
     //Cancel event handler.
        $("body").on("click", "[id*=gvCustomers] .Cancel", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    input.val(span.html());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Update").hide();
            $(this).hide();
            return false;
                 });
                 //Delete event handler.
        $("body").on("click", "[id*=gvCustomers] .Delete", function () {
            if (confirm("Do you want to delete this row?")) {
                var row = $(this).closest("tr");
                var customerId = row.find("span").html();
                $.ajax({
                    type: "POST",
                    url: "ajaxforGridview.aspx/DeleteCustomer",
                    data: '{customerId: ' + customerId + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        row.remove();
                    }
                });
            }
     
            return false;
        });
      });
        function OnSuccess(response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var customers = xml.find("Table");
            var row = $("[id*=gvCustomers] tr:last-child").clone(true);
            $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
            $.each(customers, function () {
                var customer = $(this);
                AppendRow(row, $(this).find("CustomerId").text(), $(this).find("Name").text(), $(this).find("Country").text())
                row = $("[id*=gvCustomers] tr:last-child").clone(true);
            });
        }
        function AppendRow(row, customerId, name, country) {
            //Bind CustomerId.
            $(".CustomerId", row).find("span").html(customerId);
     
            //Bind Name.
            $(".Name", row).find("span").html(name);
            $(".Name", row).find("input").val(name);
     
            //Bind Country.
            $(".Country", row).find("span").html(country);
            $(".Country", row).find("input").val(country);
            $("[id*=gvCustomers]").append(row);
        }
    
    
      
    </script>
      
    
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
               <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderText="Customer Id" ItemStyle-Width="110px" ItemStyle-CssClass="CustomerId">
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("CustomerId") %>' runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Name") %>' runat="server" />
                    <asp:TextBox Text='<%# Eval("Name") %>' runat="server" Style="display: none" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Country") %>' runat="server" />
                    <asp:TextBox Text='<%# Eval("Country") %>' runat="server" Style="display: none" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton Text="Edit" runat="server" CssClass="Edit" />
                    <asp:LinkButton Text="Update" runat="server" CssClass="Update" Style="display: none" />
                    <asp:LinkButton Text="Cancel" runat="server" CssClass="Cancel" Style="display: none" />
                    <asp:LinkButton Text="Delete" runat="server" CssClass="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
        <tr>
            <td style="width: 150px">
                Name:<br />
                <asp:TextBox ID="txtName" runat="server" Width="140" />
            </td>
            <td style="width: 150px">
                Country:<br />
                <asp:TextBox ID="txtCountry" runat="server" Width="140" />
            </td>
            <td style="width: 100px">
                <br />
                <asp:Button ID="btnAdd" runat="server" Text="Add" />
            </td>
        </tr>
    </table>
    
            </div>
        </form>
    </body>
    </html>

    Aspx.cs:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace Class.Gridview
    {
        public partial class ajaxforGridview : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    //string sql = "select * from Customers";
                    //gvCustomers.DataSource = SqlHelper.ExecuteDataTable(sql);
                    //gvCustomers.DataBind();
                    DataTable dummy = new DataTable();
                    dummy.Columns.Add("CustomerId");
                    dummy.Columns.Add("Name");
                    dummy.Columns.Add("Country");
                    dummy.Rows.Add();
                    gvCustomers.DataSource = dummy;
                    gvCustomers.DataBind();
                }
            }
    
           
            [WebMethod]
            public static string GetCustomers()
            {
                string query = "SELECT CustomerId, Name, Country FROM Customers";
                SqlCommand cmd = new SqlCommand(query);
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    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 int InsertCustomer(string name, string country)
            {
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@Name, @Country) SELECT SCOPE_IDENTITY()"))
                    {
                        cmd.Parameters.AddWithValue("@Name", name);
                        cmd.Parameters.AddWithValue("@Country", country);
                        cmd.Connection = con;
                        con.Open();
                        int customerId = Convert.ToInt32(cmd.ExecuteScalar());
                        con.Close();
                        return customerId;
                    }
                }
            }
    
            [WebMethod]
            public static void UpdateCustomer(int customerId, string name, string country)
            {
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId"))
                    {
                        cmd.Parameters.AddWithValue("@CustomerId", customerId);
                        cmd.Parameters.AddWithValue("@Name", name);
                        cmd.Parameters.AddWithValue("@Country", country);
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
    
            [WebMethod]
            public static void DeleteCustomer(int customerId)
            {
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId"))
                    {
                        cmd.Parameters.AddWithValue("@CustomerId", customerId);
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
        }
    }

    It shows as below:

    Best Regards

    Wei Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 25, 2019 10:01 AM

All replies

  • User-1174608757 posted

    Hi,

    Accordigng to your description, I have made a sample here. I suggest you to use Webservice in code behind to solve  ajax request. Here is the demo , I hope it could help you.

    Mydatatable:

    Aspx:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="../Scripts/jquery-3.3.1.js"></script>
        <script>
             $(function () {
            $.ajax({
                type: "POST",
                url: "ajaxforGridview.aspx/GetCustomers",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: OnSuccess
              });
                 $("body").on("click", "[id*=btnAdd]", function () {
            var txtName = $("[id*=txtName]");
            var txtCountry = $("[id*=txtCountry]");
            $.ajax({
                type: "POST",
                url: "ajaxforGridview.aspx/InsertCustomer",
                data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var row = $("[id*=gvCustomers] tr:last-child").clone(true);
                    AppendRow(row, response.d, txtName.val(), txtCountry.val());
                    txtName.val("");
                    txtCountry.val("");
                }
            });
            return false;
        });
        $("body").on("click", "[id*=gvCustomers] .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    $(this).find("input").show();
                    $(this).find("span").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            row.find(".Delete").hide();
            $(this).hide();
            return false;
                 });
                 $("body").on("click", "[id*=gvCustomers] .Update", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    span.html(input.val());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Cancel").hide();
            $(this).hide();
     
            var customerId = row.find(".CustomerId").find("span").html();
            var name = row.find(".Name").find("span").html();
            var country = row.find(".Country").find("span").html();
            $.ajax({
                type: "POST",
                url: "ajaxforGridview.aspx/UpdateCustomer",
                data: '{customerId: ' + customerId + ', name: "' + name + '", country: "' + country + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
     
            return false;
        });
     //Cancel event handler.
        $("body").on("click", "[id*=gvCustomers] .Cancel", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    input.val(span.html());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Update").hide();
            $(this).hide();
            return false;
                 });
                 //Delete event handler.
        $("body").on("click", "[id*=gvCustomers] .Delete", function () {
            if (confirm("Do you want to delete this row?")) {
                var row = $(this).closest("tr");
                var customerId = row.find("span").html();
                $.ajax({
                    type: "POST",
                    url: "ajaxforGridview.aspx/DeleteCustomer",
                    data: '{customerId: ' + customerId + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        row.remove();
                    }
                });
            }
     
            return false;
        });
      });
        function OnSuccess(response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var customers = xml.find("Table");
            var row = $("[id*=gvCustomers] tr:last-child").clone(true);
            $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
            $.each(customers, function () {
                var customer = $(this);
                AppendRow(row, $(this).find("CustomerId").text(), $(this).find("Name").text(), $(this).find("Country").text())
                row = $("[id*=gvCustomers] tr:last-child").clone(true);
            });
        }
        function AppendRow(row, customerId, name, country) {
            //Bind CustomerId.
            $(".CustomerId", row).find("span").html(customerId);
     
            //Bind Name.
            $(".Name", row).find("span").html(name);
            $(".Name", row).find("input").val(name);
     
            //Bind Country.
            $(".Country", row).find("span").html(country);
            $(".Country", row).find("input").val(country);
            $("[id*=gvCustomers]").append(row);
        }
    
    
      
    </script>
      
    
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
               <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderText="Customer Id" ItemStyle-Width="110px" ItemStyle-CssClass="CustomerId">
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("CustomerId") %>' runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Name") %>' runat="server" />
                    <asp:TextBox Text='<%# Eval("Name") %>' runat="server" Style="display: none" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Country") %>' runat="server" />
                    <asp:TextBox Text='<%# Eval("Country") %>' runat="server" Style="display: none" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton Text="Edit" runat="server" CssClass="Edit" />
                    <asp:LinkButton Text="Update" runat="server" CssClass="Update" Style="display: none" />
                    <asp:LinkButton Text="Cancel" runat="server" CssClass="Cancel" Style="display: none" />
                    <asp:LinkButton Text="Delete" runat="server" CssClass="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
        <tr>
            <td style="width: 150px">
                Name:<br />
                <asp:TextBox ID="txtName" runat="server" Width="140" />
            </td>
            <td style="width: 150px">
                Country:<br />
                <asp:TextBox ID="txtCountry" runat="server" Width="140" />
            </td>
            <td style="width: 100px">
                <br />
                <asp:Button ID="btnAdd" runat="server" Text="Add" />
            </td>
        </tr>
    </table>
    
            </div>
        </form>
    </body>
    </html>

    Aspx.cs:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace Class.Gridview
    {
        public partial class ajaxforGridview : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    //string sql = "select * from Customers";
                    //gvCustomers.DataSource = SqlHelper.ExecuteDataTable(sql);
                    //gvCustomers.DataBind();
                    DataTable dummy = new DataTable();
                    dummy.Columns.Add("CustomerId");
                    dummy.Columns.Add("Name");
                    dummy.Columns.Add("Country");
                    dummy.Rows.Add();
                    gvCustomers.DataSource = dummy;
                    gvCustomers.DataBind();
                }
            }
    
           
            [WebMethod]
            public static string GetCustomers()
            {
                string query = "SELECT CustomerId, Name, Country FROM Customers";
                SqlCommand cmd = new SqlCommand(query);
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    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 int InsertCustomer(string name, string country)
            {
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@Name, @Country) SELECT SCOPE_IDENTITY()"))
                    {
                        cmd.Parameters.AddWithValue("@Name", name);
                        cmd.Parameters.AddWithValue("@Country", country);
                        cmd.Connection = con;
                        con.Open();
                        int customerId = Convert.ToInt32(cmd.ExecuteScalar());
                        con.Close();
                        return customerId;
                    }
                }
            }
    
            [WebMethod]
            public static void UpdateCustomer(int customerId, string name, string country)
            {
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId"))
                    {
                        cmd.Parameters.AddWithValue("@CustomerId", customerId);
                        cmd.Parameters.AddWithValue("@Name", name);
                        cmd.Parameters.AddWithValue("@Country", country);
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
    
            [WebMethod]
            public static void DeleteCustomer(int customerId)
            {
                string constr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId"))
                    {
                        cmd.Parameters.AddWithValue("@CustomerId", customerId);
                        cmd.Connection = con;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
        }
    }

    It shows as below:

    Best Regards

    Wei Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 25, 2019 10:01 AM
  • User-2054057000 posted

    You can simply put your whole GridView inside an Update Panel and everything will start working with AJAX, and there will be no page reload during any of the operations done by the GridView. 

    Moreover you can take a look on this article that tells how to Bind GridView with Paging using jQuery Load with No Page Refresh and it clearly explains the procedure in Step by Step manner. 

    Regards...

    Monday, February 25, 2019 11:13 AM