Delete Multiple Rows Records Gridview CheckBox Confirmation

This example explains how to Delete Multiple Rows Records In Gridview With CheckBox And Delete Confirmation Using C# And VB.NET In Asp.Net.

Several times while developing web applications we need to implement functionality to delete bulk / multiple rows or records in Gridview using checkbox to select rows / records to be deleted with confirmation dialog box.

In this example i am showing how to achieve it.
Delete Multiple Rows Records In Gridview With CheckBox And Delete Confirmation


You can also read how to Edit or update multiple records/rows in gridview with checkbox using C#
I've put a Delete Button in Footer row of gridview and checkbox columns using ItemTemaplate.

Html markup of the gridview is like

<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              ShowFooter="true">
     <Columns>
     <asp:TemplateField>
     <ItemTemplate>
     <asp:CheckBox ID="chkSelect" runat="server" />
     </ItemTemplate>
     <FooterTemplate>
     <asp:Button ID="btnDelete" runat="server" Text="Delete" 
              OnClick="btnDelete_Click" 
              OnClientClick="return DeleteConfirmation();"/>
      </FooterTemplate>
      </asp:TemplateField>
      <asp:BoundField DataField="ID" 
                      HeaderText="ID" 
                      SortExpression="ID" />
      <asp:BoundField DataField="Name" 
                      HeaderText="Name" 
                      SortExpression="Name" />
      <asp:BoundField DataField="Location" 
                      HeaderText="Location" 
                      SortExpression="Location" />
      </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
     SelectCommand="SELECT [ID], [Name], [Location] 
                    FROM [Details]"></asp:SqlDataSource>

The JavaScript for delete confirmation of records is
<script type="text/javascript" language="javascript">
function DeleteConfirmation()
{
if (confirm("Are you sure," 
            "you want to delete selected records ?")==true)
   return true;
else
   return false;
}
</script>

Call this javascript by assigning on OnClientClick attribute to delete button in html markup like this
<FooterTemplate>
<asp:Button ID="btnDelete" runat="server" 
            Text="Delete" 
            OnClick="btnDelete_Click" 
            OnClientClick="return DeleteConfirmation();"/>
</FooterTemplate>

In the code behind i'm using StringCollection to store ID of records to be deleted by looping through gridview rows and checking which row is selected.

C# code behind
public partial class _Default : System.Web.UI.Page 
{
//Define global Connection String
string strConnection = ConfigurationManager.ConnectionStrings
                       ["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store 
//IDs of records to be deleted 
  StringCollection idCollection = new StringCollection();
  string strID = string.Empty;

  //Loop through GridView rows to find checked rows 
   for (int i = 0; i < GridView1.Rows.Count; i++)
   {
    CheckBox chkDelete = (CheckBox)
       GridView1.Rows[i].Cells[0].FindControl("chkSelect");
            if (chkDelete != null)
            {
                if (chkDelete.Checked)
                {
                 strID = GridView1.Rows[i].Cells[1].Text;
                 idCollection.Add(strID);
                }
            }
        }

        //Call the method to Delete records 
        DeleteMultipleRecords(idCollection);

        // rebind the GridView
        GridView1.DataBind();
    }
    /// <summary>
    /// This is to Delete multiple records in gridview
    /// </summary>
    /// <param name="idCollection">stringCollection</param>
private void DeleteMultipleRecords
                            (StringCollection idCollection)
{
//Create sql Connection and Sql Command
 SqlConnection con = new SqlConnection(strConnection);
 SqlCommand cmd = new SqlCommand();
 string IDs = "";

foreach (string id in idCollection)
{
  IDs += id.ToString() + ",";
}
          try
            {
               string strIDs = 
                IDs.Substring(0, IDs.LastIndexOf(","));
                   string strSql = "Delete from Details 
                           WHERE ID in (" + strIDs + ")";
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strSql;
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                string errorMsg = "Error in Deletion";
                errorMsg += ex.Message;
                throw new Exception(errorMsg);
            }
            finally
            {
                con.Close();
            }
}
    
}

Another Method
We can also use sqlDataSource delete method to delete multiple records in following way
add delete command and delete Parameters in SqlDataSource html markup
Add DataKeyNames in GridView html source
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              ShowFooter="true" DataKeyNames="ID">
Now add Delete command
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
     SelectCommand="SELECT [ID], [Name], [Location] 
                    FROM [Details] 
         DeleteCommand="Delete from [Details] where [ID]=@ID">
<DeleteParameters>
<asp:Parameter Name="ID"/>
</DeleteParameters>">
</asp:SqlDataSource>
Now write this code in click event of Delete button in code behind
foreach(GridViewRow row in GridView1. Rows)
{
CheckBox chkDelete = (CheckBox)row.FindControl
                                ("chkSelect");
if(chkDelete.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys
                       [row.RowIndex].Value);
SqlDataSource1.DeleteParameters["ID"]
         .DefaultValue = customerid.ToString();
SqlDataSource1.Delete();
}

} 

VB.NET code
Public Partial Class _Default
    Inherits System.Web.UI.Page
    'Define global Connection String
    Private strConnection As String 
                   = ConfigurationManager.ConnectionStrings
        ("ConnectionString").ConnectionString
    Protected Sub Page_Load
(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnDelete_Click
(ByVal sender As Object, ByVal e As EventArgs)
        'Create String Collection to store 
        'IDs of records to be deleted 
        Dim idCollection As New StringCollection()
        Dim strID As String = String.Empty
        
        'Loop through GridView rows to find checked rows 
        For i As Integer = 0 To GridView1.Rows.Count - 1
            Dim chkDelete As CheckBox = 
DirectCast(GridView1.Rows(i).Cells(0).FindControl
              ("chkSelect"), CheckBox)
            If chkDelete IsNot Nothing Then
                If chkDelete.Checked Then
                    strID = GridView1.Rows(i).Cells(1).Text
                    idCollection.Add(strID)
                End If
            End If
        Next
        
        'Call the method to Delete records 
        DeleteMultipleRecords(idCollection)
        
        ' rebind the GridView
        GridView1.DataBind()
    End Sub
    ''' <summary>
    ''' This is to Delete multiple records in gridview
    ''' </summary>
    ''' <param name="idCollection">stringCollection</param>
    Private Sub DeleteMultipleRecords
(ByVal idCollection As StringCollection)
        'Create sql Connection and Sql Command
        Dim con As New SqlConnection(strConnection)
        Dim cmd As New SqlCommand()
        Dim IDs As String = ""
        
        'Create string builder to store 
        'delete commands separated by ;
        
        For Each id As String In idCollection
            IDs += id.ToString() & ","
        Next
        
        Try
            Dim strIDs As String = 
IDs.Substring(0, IDs.LastIndexOf(","))
            Dim strSql As String = 
("Delete from Details" & +" WHERE ID in (") + strIDs & ")"
            cmd.CommandType = CommandType.Text
            'cmd.CommandText = sbStrCommand.ToString();
            cmd.CommandText = strSql
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
        Catch ex As SqlException
            Dim errorMsg As String = "Error in Deletion"
            errorMsg += ex.Message
            Throw New Exception(errorMsg)
        Finally
            con.Close()
            
            
        End Try
    End Sub
    
End Class

Hope this helps

Other Posts on ASP.NET:
1. ASP.NET-Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate
2. Data Transfer to other aspx pages using Query String Session cookies and cross page posting
3. Data Transfer Using Cookies Session Variables Cross page posting and QueryStrings in ASP.NET
4. Cross page posting, Submit Form and Server.Transfer methods in ASP .NET for data transfer
5. Pouplating Multiple DetailsView based on single GridView using DataKeyNames in ASP.NET
If you like this post than join us or share

30 comments:

itismovie said...

pls send me your counter.php file to itismovie@gmail.com tnx.


prashant said...

nice work dude, you are doing great.


Anonymous said...

hi, i use ObjectDataSource. but GridView doesn't Refresh Data after i clik on button Delete! wat wrong?


Unknown said...

@Anonymous :

I Think u have forgot to rebind the grid after deleting the record in click event of delete button, you need to rebind the grid either by writing a method and call it at last in delete button click event or try using
YourGridViewName.DataBind()

DO let me know if this doesn't fix you issue


Anonymous said...

Perfect!


Anonymous said...

Hi, i am using the same method as u which use template field datagridview, but i am using image button in each row and delete that particular row after i click tat image button

can u tell me how to get the data/key for that particular row i have click?

Thank in advance


Anonymous said...

This comment has been removed by a blog administrator.


Anonymous said...

Nice!


Anonymous said...

we've 2 gridviews on same page with checkbox,now as we delete the selected row the data of particular row from gridview1 is to be inserted in grid view2. can u tell me the solution as soon as possible


Anonymous said...

I have ask: What happen when user not selected any row?? Confirm dialog still shows, isn't it???


Anonymous said...

Hi,
Your code is helpfull to me. And I want to ask how to check if have any checkbox is checked before show Message box confirm. How to do?

Thanks a lot


Anonymous said...

It is extremely interesting for me to read the blog. Thanks for it. I like such topics and everything that is connected to them. I definitely want to read a bit more soon.


Sunita Badsra said...

nice ,keep it up


Rafael Cardoso said...

This is easy writing the GridView code in ASP. Try to do it on code-behind and you'll have problems to get checked checkboxes.


Anonymous said...

Don't stop posting such stories. I love to read articles like this. By the way add some pics :)


Anonymous said...

I truly believe that we have reached the point where technology has become one with our world, and I am fairly certain that we have passed the point of no return in our relationship with technology.


I don't mean this in a bad way, of course! Societal concerns aside... I just hope that as technology further innovates, the possibility of transferring our memories onto a digital medium becomes a true reality. It's a fantasy that I daydream about all the time.


(Posted on Nintendo DS running [url=http://www.leetboss.com/video-games/r4i-r4-sdhc-nintendo-ds]R4i[/url] DS SKu2)


Anonymous said...

You guys are awesome! Great post!


adolf said...

vb.net code not working in my page


viagra online said...

hello that's information was to useful in my case, I have a lot of problems and when I saw this page all may problems is gonna directly to hell.


Anonymous said...

hi


Sunil Jain said...

Thanks for the Code. Plz add the code for multiple checkbox selection, only then it will be nice.


Anonymous said...

Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.


Anonymous said...

Its still not happening..I am doing it in Vb.Net & connecting it with Ms Access but its still not getting deleted..!!..Please help.

Thank You.


Unknown said...

Its still not happening..I am doing it in Vb.Net & connecting it with Ms Access but its still when i click on delete button its not getting deleted..!!..Please help.

Thank You.


Anonymous said...

Its still not happening..I am doing it in Vb.Net & connecting it with Ms Access but still when i press on delete button its not getting deleted..!!..Please help.

Thank You.


Anonymous said...

Thanks for posting this info, Amit. You saved me time!


Sumitha.V.R said...

Really this is good Article. This is exact coding which I expected.Thanks


srinivas said...

AHi Amit,
It's a great post.Thanks for this.And i have a requirement with Linq to sql.Can you please provide me the code for multiple checkbox selection with deletion option using linq to sql?

Thanks in Advance


Anonymous said...

Thank you
This Code Work well even I am using Stroe Procedure with minnor changes.
Once again thanx


Anonymous said...

hi........
good post..............


Find More Articles