Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Delete Gridview Rows in Asp.net using Checkbox in C#, VB.NET

Nov 26, 2014
Introduction

Here I will explain how to delete
gridview rows in asp.net using checkbox using c# , vb.net with confirmation message or how to delete multiple rows from gridview using checkbox selection with confirmation in asp.net using c# , vb.net.

Description:
  
In previous articles I explained Get gridview selected row cell value in asp.net, Get Controls inside of gridview in asp.net,
Bind data to textbox in gridview in asp.net, export gridview data to excel in asp.net using c# , export gridview data to pdf in asp.net using c# and many articles relating to gridview, asp.net, c#,vb.net and jQuery. Now I will explain how to delete gridview row in asp.net using checkbox using c# , vb.net with confirmation message.

Before implement this example first design one table UserDetails in your database as shown below

Column Name
Data Type
Allow Nulls
UserId
Int(IDENTITY=TRUE)
Yes
UserName
varchar(50)
Yes
FirstName
varchar(50)
Yes
LastName
varchar(50)
Yes
Once table created in database enter some dummy data to test application after that write the following code in your aspx page 


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>how to delete gridview row in asp.net using checkbox</title>
<script type="text/javascript">
function Confirmationbox() {
var result = confirm('Are you sure you want to delete selected User(s)?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="FirstName" DataField="FirstName" />
<asp:BoundField HeaderText="LastName" DataField="LastName" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnDelete" Text="Delete Selected Records" runat="server" Font-Bold="true" OnClientClick="javascript:return Confirmationbox();" onclick="btnDelete_Click" />
</div>
</form>
</body>
</html>
Now open code behind file and write the following code

C# Code


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

public partial class DeleteGridviewRows : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUserDetails();
        }
    }
    protected void BindUserDetails()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Select * from UserDetails", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            con.Close();
        }
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvrow in gvDetails.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 UserId of particular row using datakey value
                int usrid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value);
                using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + usrid, con);
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
            BindUserDetails();
    }
}
VB.NET


Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls
Partial Class VBCode
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindUserDetails()
        End If
    End Sub
    Protected Sub BindUserDetails()
        Dim dt As New DataTable()
        Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
            con.Open()
            Dim cmd As New SqlCommand("Select * from UserDetails", con)
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            con.Close()
        End Using
        gvDetails.DataSource = dt
        gvDetails.DataBind()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        For Each gvrow As GridViewRow In gvDetails.Rows
            'Finiding checkbox control in gridview for particular row
            Dim chkdelete As CheckBox = DirectCast(gvrow.FindControl("chkSelect"), CheckBox)
            'Condition to check checkbox selected or not
            If chkdelete.Checked Then
                'Getting UserId of particular row using datakey value
                Dim usrid As Integer = Convert.ToInt32(gvDetails.DataKeys(gvrow.RowIndex).Value)
                Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
                    con.Open()
                    Dim cmd As New SqlCommand("delete from UserDetails where UserId=" & usrid, con)
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using
            End If
        Next
        BindUserDetails()
    End Sub
End Class
Demo

Delete Gridview Row in Asp.net using Checkbox in C#, VB.NET


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

4 comments :

Anonymous said...

This is an excellent article.
Thank you very much for taking the time to publish
Regards
Eddie

Unknown said...

when i click on delete button the gridview is redirecting to another page

Anonymous said...

Its not working... it did not check gird view row

Shuuriye jr said...

Absolutely Great
Thanks for your help
Best regards

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.