News
* IBM to offer mobile security as a service IBM will start delivering mobile security-as-a-service (MaaS) through its own cloud infrastructure in India, a move that is expected to better address in-country data requirements... IBM Spectrum Computing: IBM has enlarged its portfolio of software-defined infrastructure solutions with cognitive features for workload management.  * LiFi internet technology has been introduced, the new type of wireless internet connection that gives 100 times faster than traditional WiFi -- Invented by Professor Harald Haas from the University of Edinburgh. * Sci. Rachid Yazami has developed a smart chip that charges smartphones in less than 10 minutes. BenQ has launched BlueCore projector - Consumer electronics major BenQ has launched its first BlueCore laser light source projector. For those unaware, devices with BlueCore laser technology have a high contrast output of 80000:1 with an extended lamp life and efficiency. *** 
  Jan 25 2015 9:41AM     Michael Ryan
  0 Comments    13842 Views  
Here Michael Ryan provided a short tutorial with example, how to delete row from gridview using Checkbox on Button Click in ASP.Net
Database
For binding the gridview, First have to create a table in Microsoft SQL Server Database as shown below.
Creating a table
When creating a table make Identity Specification as true for column 'ID'.

Set the table name as shown below.
Adding a GridView to the Page
Firstly you need to add a GridView control to the ASP.Net Web Page from the Visual Studio ToolBox as shown below.

HTML
Below is the sample HTML code,

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function Confirmationbox() {
            var result = confirm('Are you sure you want to delete selected Employee(s)?');
            if (result) {
                return true;
            }
            else {
                return false;
            }
        }
    </script> 
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>
            Employee Details</h2>
        <br >
        <asp:GridView ID="GridEmployee" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" CellPadding="5" style="background-color: rgb(241, 241, 241);">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkSelect" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="EmployeeID" DataField="ID" />
                <asp:BoundField HeaderText="Name" DataField="EmployeeName" />
                <asp:BoundField HeaderText="Age" DataField="EmployeeAge" />
                <asp:BoundField HeaderText="Age" DataField="EmployeeDesc" />
                <asp:BoundField HeaderText="Experience" DataField="EmployeeExperience" />
            </Columns>
            <HeaderStyle BackColor="#81B441" Font-Bold="true" ForeColor="White" />
        </asp:GridView>
    </div>
    <br >
    <br >
    <asp:Button ID="btnDelete" runat="server" Text="Delete Selected Rows" OnClientClick="javascript:return Confirmationbox();"  
    OnClick="btnDelete_Click" style="color: Black; font-size:12px; font-weight: bold; height:30px;" />

    </form>
</body>
</html>

XML
Below is the sample Web.config file Code,

<configuration>
  <connectionStrings>
    <add name="ConnectionString" connectionString="server=SERVER-NAME;database=DATABASE-NAME;uid=USER-ID;password=PASSWORD;"/>   
  </connectionStrings>

Namespaces
You will need to import the following namespace.
C#

using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;

VB

Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Text

Delete row from Gridview using Checkbox
Below is the sample code to Delete row from Gridview using Checkbox in ASP.Net C#/VB.
C#

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridview();              
            }
        }

        // GetData From dataset and return as Dataset
        private DataSet GetData(string query)
        {
            string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlCommand cmd = new SqlCommand(query);
            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        return ds;
                    }
                }
            }
        }

        // Bind Gridview 
        public void BindGridview()
        {
            GridEmployee.DataSource = GetData("SELECT ID,EmployeeName, EmployeeAge, EmployeeDesc, EmployeeExperience FROM Employee");
            GridEmployee.DataBind(); 
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow gvrow in GridEmployee.Rows)
            {
                //Finiding checkbox control in gridview for particular row
                CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkSelect");
                //Condition to check checkbox selected or not
                if (chkdelete.Checked)
                {
                    //Getting EmployeeID of particular row using datakey value
                    int EmployeeID = Convert.ToInt32(GridEmployee.DataKeys[gvrow.RowIndex].Value);
                    //Getting Connection String from Web.Config
                    string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(conString))
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("DELETE FROM Employee where ID=" + EmployeeID, con);
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
            BindGridview();
        }

VB

Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)

        If Not IsPostBack Then
            BindGridview()
        End If

    End Sub
    
    Private Function GetData(ByVal query As StringAs DataSet

        Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
        Dim cmd  SqlCommand = New (query)
        Dim con  SqlConnection = New (conString)
        Dim sda  SqlDataAdapter = New SqlDataAdapter()
        cmd.Connection = con
        sda.SelectCommand = cmd
        Dim ds  DataSet = New DataSet()
        sda.Fill(ds)
        Return ds

    End Function
    
    Public Sub BindGridview()

        GridEmployee.DataSource = GetData("SELECT ID,EmployeeName, EmployeeAge, EmployeeDesc, EmployeeExperience FROM Employee")
        GridEmployee.DataBind()

    End Sub
    
    Protected Sub btnDelete_Click(ByVal sender As ObjectByVal e As EventArgs)

        For Each gvrow As GridViewRow In GridEmployee.Rows
            'Finiding checkbox control in gridview for particular row
            Dim chkdelete As CheckBox = CType(gvrow.FindControl("chkSelect"),CheckBox)
            'Condition to check checkbox selected or not
            If chkdelete.Checked Then
                'Getting EmployeeID of particular row using datakey value
                Dim EmployeeID As Integer = Convert.ToInt32(GridEmployee.DataKeys(gvrow.RowIndex).Value)
                'Getting Connection String from Web.Config
                Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
                Dim con  SqlConnection = New (conString)
                con.Open()
                Dim cmd  SqlCommand = New (("DELETE FROM Employee where ID=" + EmployeeID), con)
                cmd.ExecuteNonQuery()
                con.Close()
            End If
        Next
        BindGridview()

    End Sub

Result
I hope this page will helps to delete rows in Gridview using Checkbox in ASP.Net application. Thanks.
BackToTop
Comments



 
Search
Recent Posts
Create Amazon ElasticCache Using Memcached in CSharp
Oct 29 2018 12:09PM Posted By Amose
Get Google Map Lat Lng (Geo Point) By Pincode in C#
Oct 28 2018 12:09PM Posted By Pranav
Google URL Shortener in C#
Oct 20 2018 12:09PM Posted By Sanjay
Bind Gridview from CSV file in Asp.Net C#
Oct 5 2018 12:09PM Posted By Michael
Call WebService method from jQuery in every 1 minute
Sep 26 2018 12:09PM Posted By John
Gridview custom CSS in ASP.Net
Sep 14 2018 12:09PM Posted By Micheal Ryan
Read excel file and bind to Gridview in C#
Sep 10 2018 12:09PM Posted By Micheal
Tags
Follow us on Facebook
Follow us on Google +
Recent post in your Email inbox.
Enter your email address: