Hi arujvedia,
Change the jQuery selector for Insert, Edit, Update and Delete.
Please refer below sample.
For this sample i have used below article.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<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>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.1.min.js"
integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
});
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var row = $("[id*=gvCustomers] tr:last-child");
if (customers.length > 0) {
$.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);
});
} else {
row.find(".Edit").hide();
row.find(".Delete").hide();
row.find("span").html(' ');
}
}
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);
row.find(".Edit").show();
row.find(".Delete").show();
$("[id*=gvCustomers]").append(row);
}
//Add event handler.
$("[id*=btnAdd]").on("click", function () {
var txtName = $("[id*=txtName]");
var txtCountry = $("[id*=txtCountry]");
$.ajax({
type: "POST",
url: "CS.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");
if ($("[id*=gvCustomers] tr:last-child span").eq(0).html() != " ") {
row = row.clone();
}
AppendRow(row, response.d, txtName.val(), txtCountry.val());
txtName.val("");
txtCountry.val("");
}
});
return false;
});
//Edit event handler.
$("[id*=gvCustomers] .Edit").on("click", 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;
});
//Update event handler.
$("[id*=gvCustomers] .Update").on("click", 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: "CS.aspx/UpdateCustomer",
data: '{customerId: ' + customerId + ', name: "' + name + '", country: "' + country + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return false;
});
//Cancel event handler.
$("[id*=gvCustomers] .Cancel").on("click", 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.
$("[id*=gvCustomers] .Delete").on("click", 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: "CS.aspx/DeleteCustomer",
data: '{customerId: ' + customerId + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("[id*=gvCustomers] tr").length > 2) {
row.remove();
} else {
row.find(".Edit").hide();
row.find(".Delete").hide();
row.find("span").html(' ');
}
}
});
}
return false;
});
</script>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindDummyRow();
}
}
private void BindDummyRow()
{
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["constr"].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["constr"].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["constr"].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["constr"].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();
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindDummyRow()
End If
End Sub
Private Sub BindDummyRow()
Dim dummy As New DataTable()
dummy.Columns.Add("CustomerId")
dummy.Columns.Add("Name")
dummy.Columns.Add("Country")
dummy.Rows.Add()
gvCustomers.DataSource = dummy
gvCustomers.DataBind()
End Sub
<WebMethod()>
Public Shared Function GetCustomers() As String
Dim query As String = "SELECT CustomerId, Name, Country FROM Customers"
Dim cmd As New SqlCommand(query)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using ds As New DataSet()
sda.Fill(ds)
Return ds.GetXml()
End Using
End Using
End Using
End Function
<WebMethod()>
Public Shared Function InsertCustomer(name As String, country As String) As Integer
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As 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()
Dim customerId As Integer = Convert.ToInt32(cmd.ExecuteScalar())
con.Close()
Return customerId
End Using
End Using
End Function
<WebMethod()>
Public Shared Sub UpdateCustomer(customerId As Integer, name As String, country As String)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As 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()
End Using
End Using
End Sub
<WebMethod()>
Public Shared Sub DeleteCustomer(customerId As Integer)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId")
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Screenshot