In this article I will explain how to delete row from GridView and database using jQuery in ASP.Net, C# and VB.Net.
When the delete button is clicked, a JavaScript confirmation box will be displayed and once confirmed a jQuery AJAX call will be made to the WebMethod which will then execute a DELETE query on the database table.
Once the record is deleted successfully from database, the corresponding row will be removed from GridView using jQuery.
 
Database
I have created a simple table named Customers whose schema is shown below
Delete Row from GridView and Database using jQuery in ASP.Net
And then I have inserted few records in the table as shown below.
Delete Row from GridView and Database using jQuery in ASP.Net
 
Note: The SQL for creating the table is provided in the attached sample code.
 
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView with a LinkButton placed inside TemplateField column for deleting the GridView Row.
You will notice that I have assigned the CustomerId field to a HiddenField, this HiddenField will be used to fetch the CustomerId while deleting the GridView Row using jQuery.
<asp:GridView ID="GridView1"runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField DataField="CustomerId" HeaderText="Id" HeaderStyle-Width="30"/>
    <asp:BoundField DataField="Name" HeaderText="Name" HeaderStyle-Width="150"/>
    <asp:BoundField DataField="Country" HeaderText="Country" HeaderStyle-Width="150"/>
    <asp:TemplateField HeaderStyle-Width="50">
        <ItemTemplate>
            <asp:HiddenField ID="hfCustomerId" runat="server" Value='<%# Eval("CustomerId") %>'/>
            <asp:LinkButton ID="lnkDelete" Text="Delete" runat="server"/>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
 
VB.Net
Imports System.Data
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
 
 
Populating the GridView
The GridView is populated with records from the Customers table inside the Page Load event.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                DataTable dt = new DataTable();
                sda.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(conString)
        Using cmd As New SqlCommand("SELECT * FROM Customers")
            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Dim dt As New DataTable()
                sda.Fill(dt)
                GridView1.DataSource = dt
                GridView1.DataBind()
            End Using
        End Using
    End Using
End Sub
 
Delete Row from GridView and Database using jQuery in ASP.Net
 
WebMethod for deleting the GridView Row from Database
The following WebMethod will be used for deleting the records from the database table. It accepts CustomerId as parameter which will be passed by the jQuery AJAX call.
Using the CustomerId a delete query is executed and the record gets deleted from the database table.
C#
[WebMethod]
public static bool DeleteCustomer(int customerId)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId"))
        {
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@CustomerId", customerId);
            con.Open();
            int rowsAffected = cmd.ExecuteNonQuery();
            con.Close();
            return rowsAffected > 0;
        }
    }
}
 
VB.Net
<WebMethod> _
Public Shared Function DeleteCustomer(customerId As Integer) As Boolean
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(conString)
        Using cmd As New SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId")
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@CustomerId", customerId)
            con.Open()
            Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
            con.Close()
            Return rowsAffected > 0
        End Using
    End Using
End Function
 
 
jQuery Implementation for deleting the GridView row from Database
Following is the jQuery Client side implementation to delete the GridView row from database. A jQuery click event handler has been assigned to the Delete LinkButton inside the GridView.
Inside the jQuery click event handler, a JavaScript confirmation is raised and if the response is positive then the GridView row to be deleted is identified.
Using the reference of the row, the CustomerId is fetched from the Hidden Field and passed as parameter to the jQuery AJAX call made to the WebMethod.
Inside the success event handler of the jQuery AJAX call, the GridView row is removed and if all the GridView rows have been deleted then a “No records found” message is displayed.
Finally a JavaScript alert message box is displayed which displays the success message to the user.
Note: In order to track down server side exceptions and errors when using jQuery AJAX call, please refer my article Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net.
 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("[id*=GridView1] [id*=lnkDelete]").click(function () {
        if (confirm("Do you want to delete this Customer?")) {
            //Determine the GridView row within whose LinkButton was clicked.
            var row = $(this).closest("tr");
 
            //Look for the Hidden Field and fetch the CustomerId.
            var customerId = parseInt(row.find("[id*=hfCustomerId]").val());
 
            //Make an AJAX call to server side and pass the fetched CustomerId.
            $.ajax({
                type: "POST",
                url: "Default.aspx/DeleteCustomer",
                data: '{customerId: ' + customerId + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    if (r.d) {
                        //Remove the row from the GridView.
                        row.remove();
                        //If the GridView has no records then display no records message.
                        if ($("[id*=GridView1] td").length == 0) {
                            $("[id*=GridView1] tbody").append("<tr><td colspan = '4' align = 'center'>No records found.</td></tr>")
                        }
                        alert("Customer record has been deleted.");
                    }
                }
            });
        }
        return false;
    });
});
</script>
 
 
Screenshots
JavaScript confirmation when the delete button is clicked
Delete Row from GridView and Database using jQuery in ASP.Net
 
JavaScript alert message when row is successfully deleted from database
Delete Row from GridView and Database using jQuery in ASP.Net
 
“No records found” message when GridView does not have records
Delete Row from GridView and Database using jQuery in ASP.Net
 
Demo
 
Downloads