Delete Multiple Rows of GridView using Checkbox in Asp.Net C# VB.Net

You knew that GridView allow us to delete a single row at a time. Here i would like to show you “How we can Delete Multiple GridView Rows like Gmail Deletion“. To do that add an extra template column in GridView to add the Checkboxes. So that user can check the Checkboxes to make his multiple selection for deletion. Plus I will discuss on deletion problem of master child data later on this article. This is a complete step by step article on “Deleting Multiple Records at a time from a GridView”. No other help is required to complete this example.

Delete Multiple rows of GridView using Checkbox in Asp.Net CSharp VB.Net

First create a Database Table:

CREATE TABLE [dbo].[tblBrand](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
	[Status] [bit] NOT NULL,

Now Insert some Data into the Database:

INSERT INTO tblBrand VALUES(1,'Uniliver',1)
INSERT INTO tblBrand VALUES(2,'Procter & Gamble',1)
INSERT INTO tblBrand VALUES(3,'Shohag',1)
INSERT INTO tblBrand VALUES(4,'Kohinoor',1)
INSERT INTO tblBrand VALUES(5,'Akij',1)

Now configure Web.Config File to create Database Connection:

    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now Add Full HTML Markup Like Below:

<script type="text/javascript">
    function GridSelectAllColumn(spanChk) {
        var oItem = spanChk.children;
        var theBox = (spanChk.type == "checkbox") ? spanChk : spanChk.children.item[0]; xState = theBox.checked;
        elm = theBox.form.elements;

        for (i = 0; i < elm.length; i++) {
            if (elm[i].type === 'checkbox' && elm[i].checked != xState)

<asp:GridView runat="server" ID="gvBrand" DataKeyNames="ID" AutoGenerateColumns="false" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
        <asp:TemplateField HeaderText="Select">
        <asp:CheckBox runat="server" ID="chk"/>
        <ItemStyle BackColor="#DCE8FA" HorizontalAlign="Center" />
        <HeaderStyle HorizontalAlign="Center" />
        <input id="chkAll" onclick="javascript:GridSelectAllColumn(this, 'chk');" runat="server" type="checkbox" value="" />
        <asp:BoundField DataField="Name" HeaderText="Name">
        <asp:BoundField DataField="Status" HeaderText="Status">

<asp:Button runat="server" ID="cmdDlete" Text="Delete"
 OnClientClick="return confirm('Are you sure to delete?')" OnClick="cmdDlete_Click" />

Note: Javascript Function GridSelectAllColumn() will help us to check or uncheck all Checkboxes. Delete button OnClientClick event help us to prompt user that system going to permanently delete selected records.

Now Bind the GridView with Database Data:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)

    private void RefreshGridView()
        DataTable dt = new DataTable();
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            SqlDataAdapter ad = new SqlDataAdapter("SELECT * from tblBrand", conn);
            ViewState["dtSupplier"] = dt;

        gvBrand.DataSource = dt;

Note: Here I have separated the GridView databind method from Page_Load event because after deletion we need to rebind the GridView again. Don’t forget to add “System.Configuration”,”System.Data”,”System.Data.SqlClient” namespaces.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
        End If
    End Sub

    Protected Sub RefreshGridView()
        Dim dt As DataTable = New DataTable()
        Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)
            Dim ad As SqlDataAdapter = New SqlDataAdapter("SELECT * from tblBrand", conn)
            ViewState("dtSupplier") = dt
        End Using

        gvBrand.DataSource = dt
    End Sub

Note: Here I have separated the GridView databind method from Page_Load event because after deletion we need to rebind the GridView again. Don’t forget to add “System.Configuration”,”System.Data”,”System.Data.SqlClient” namespaces.

Now Add a Class for re usability to Perform the Deletion:
Give the class name “DBUtility”.
C# Code:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;

public class DBUtility
	public DBUtility()

    public bool PerformDelete(GridView GV, string sTableName)
        bool bSaved = false;
        string sClause = "''";
        string sSQL = "";
        SqlConnection Conn;
        SqlCommand comm;

        string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        foreach (GridViewRow oItem in GV.Rows)
            if (((CheckBox)oItem.FindControl("chk")).Checked)
                sClause += "," + GV.DataKeys[oItem.DataItemIndex].Value;

        sSQL = "DELETE FROM " + sTableName + " WHERE " + GV.DataKeyNames.GetValue(0) + " IN(" + sClause + ")";
        Conn = new SqlConnection(sConstr);
        using (Conn)
                comm = new SqlCommand(sSQL, Conn);
                using (comm)
                    comm.CommandTimeout = 0;
                    bSaved = true;
        return bSaved;

Note: Don’t forget to add above mentioned namespaces.

VB.Net Code:

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI

Public Class DBUtility

    Public Function PerformDelete(GV As GridView, sTableName As String) As Boolean
        Dim bSaved As Boolean = False
        Dim sClause As String = "''"
        Dim sSQL As String = ""
        Dim comm As SqlCommand

        Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString

        For Each oItem As GridViewRow In GV.Rows
            If CType(oItem.FindControl("chk"), CheckBox).Checked Then
                sClause += "," + GV.DataKeys(oItem.DataItemIndex).Value.ToString()
            End If

        sSQL = "DELETE FROM " + sTableName + " WHERE " + GV.DataKeyNames.GetValue(0) + " IN(" + sClause + ")"
        Using conn As SqlConnection = New SqlConnection(sconstr)
            comm = New SqlCommand(sSQL, conn)
            Using comm
                comm.CommandTimeout = 0
                bSaved = True
            End Using
        End Using
        Return bSaved
    End Function
End Class

Note: Don’t forget to add above mentioned namespaces.

Now run the project. Hope you can perform multiple deletion at a time.

Why i add this extra class to delete multiple rows from Griview? Because most of the developers need to do this in the maximum number of pages of a project. If I can write a common method to handle each deletion then it will keep our code clean & more manageable. I knew that lot of architecture now available to ensure the re usability of code but for a beginner i think the above stated way is more easier. After that he can incorporate the above code segment into his DAL. For an example: I want to develop an Ecommerce site where i will sale different type of products. If I don’t consider product stock then only the order module or shopping cart is the transactional page but the rest of the pages were basic data entry page like Category, Brand, Customer, Product, Product variation, Kit etc. In all of this page, either user or admin need to perform Multiple Deletion. And using this class you just instantiate the object & pass the GridView reference to the PerformDelete() method. That’s it, just 2 lines of code will take care all deletion issues.

Another concern:
Most of the times developer has a problem to delete master table data since there is a relation between master child table data. Look at my above example if i have a reference table named Product to Brand table then you can not delete Brand table data. You will receive the below error:
The DELETE statement conflicted with the REFERENCE constraint “FK_tblProduct_tblBrand”. The conflict occurred in database “XXXX”, table “dbo.tblProduct”, column ‘BrandID’.
The statement has been terminated.

Fig: Relationship between Brand & Product.

Hope now you can understand why error occurred. To resolve this issue we have two options:
1. Add ON DELETE CASCADE constraint.
2. Delete first child data.

Add “ON DELETE CASCADE” constraint:
If you add ON DELETE CASCADE constraint into a table then child data automatically deleted when user perform any delete operation on its master table. This is easy but a bit risky. To do that first DROP the foreign key constraint like:

ALTER TABLE tblProduct
DROP CONSTRAINT FK_tblProduct_tblBrand

Now add “ON DELETE CASCADE” constraint in the following way:

ALTER TABLE tblProduct
ADD CONSTRAINT FK_tblProduct_tblBrand

Hope now you can handle each issues on deletion for all basic entry pages.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, Client, Gridview, Javascript, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *