Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 366, trackbacks - 0

My Links

News

Archives

Image Galleries

GridView Multiple Delete with CheckBox and Confirm

This demo describes how to implement multiple delete in GridView using CheckBox control and display a confirmation message.
Assuming that we have this GridView column mark up below
<Columns>
   <asp:TemplateField>
   <HeaderTemplate>
      <asp:Button ID="ButtonDelete" runat="server" Text="Delete" />
   </HeaderTemplate>
   <ItemTemplate>
      <asp:CheckBox ID="CheckBox1" runat="server" />
   </ItemTemplate>
   </asp:TemplateField>
   <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="True" />
   <asp:BoundField DataField="CompanyName" HeaderText="Company"/>
   <asp:BoundField DataField="ContactName" HeaderText="Name"/>
   <asp:BoundField DataField="ContactTitle" HeaderText="Title" />
   <asp:BoundField DataField="Address" HeaderText="Address"/>
   <asp:BoundField DataField="Country" HeaderText="Country"/>
</Columns>
 
For binding your GridView with data I would suggest you to refer to my previous example about “Binding GridView with data from Database”
Now let’s create our method for deleting. First we need to declare the following namespaces below in order for us to use the SqlClient libraries, StringBuilder and StringCollection class.
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
 
Here’s the code block for the deleting multiple records method
#region Multiple Delete
private void DeleteRecords(StringCollection sc)
{
   SqlConnection conn = new SqlConnection(GetConnectionString());
   StringBuilder sb = new StringBuilder(string.Empty);
 
   foreach (string item in sc)
   {
     const string sqlStatement = "DELETE FROM Customers WHERE CustomerID";
     sb.AppendFormat("{0}='{1}'; ",sqlStatement, item);
   }
   try
   {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
            string msg = "Deletion Error:";
            msg += ex.Message;
            throw new Exception(msg);
     }
     finally
     {
            conn.Close();
     }
}
#endregion
 
The DeleteRecords() method takes one parameter which is basically a string collections of ID to be deleted. The method basically iterates all the ID that was stored in the StringCollection object. Those values stored in the String collections will be formatted together with the value of sqlStatements string and creates a concatenated delete statements based from the number of ID’s to be deleted. These concatenated values are then stored in the StringBuilder object and pass it in the SqlCommand as a parameter.
I used this approach so that we can execute multiple deletes at once and this way we only need to hit the database once.
Now let’s call DeleteRecords() method at the Delete Button_Click event of GridView that was located at the Header portion of the first column of the GridView. In order to generate the click event automatically you follow these few steps below:
1.       Switch to Design View in the Visual Studio Designer
2.       Right Click on the GridView and Select Edit Template -- > Column[0]
3.       Then the GridView will switch to edit mode
4.       Find the Delete Button in the Template and Double Click on the button to generate the event for you
5.       Then write the codes there for calling the Delete method and so on
6.       To switch back to default mode in GridView then just right click on the GridView and Select End Template Editing
7.       Then you are done
Here’s the code block for the Delete Button_Click event below
protected void ButtonDelete_Click(object sender, EventArgs e)
{
 StringCollection sc = new StringCollection();
 string id = string.Empty;
 
 for (int i = 0; i < GridView1.Rows.Count; i++)//loop the GridView Rows
 {
      CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1"); //find the CheckBox
      if (cb != null)
      {
         if (cb.Checked)
          {
            id = GridView1.Rows[i].Cells[1].Text; // get the id of the field to be deleted
            sc.Add(id); // add the id to be deleted in the StringCollection
           }
        }
      }
 
     DeleteRecords(sc); // call method for delete and pass the StringCollection values
     BindGridView(); // Bind GridView to reflect changes made here
}
 
The code above basically loops through the GridView rows and search for the TextBox was checked using FindControl() method. When a CheckBox is checked it will then get the corresponding ID for that row and add it in the StringCollection object. After it loops through all the CheckBox that was checked then we call the DeleteRecords() method to perform the deletion.
Note: Don’t forget to Bind your GridView with data after you call the delete method to reflect the changes in the GridView.
Now let’s create a confirmation message when a user attempts to delete records. I would also suggest you to read my previous example about “Display Confirmation on GridView Deleting”.
Here’s the JavaScript function for the delete confirmation.
<head runat="server">
    <title>GridView Data Manipulation</title>
    <script type="text/javascript" language="javascript">
        function ConfirmOnDelete(item)
        {
          if (confirm("The following item(s) will be deleted: " + item + "Continue?")==true)
            return true;
          else
            return false;
        }
    </script>
</head>
 
Here’s the code behind for calling the JavaScript function at RowDataBound event of GridView
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.Header) //check for RowType
        {
            Button b = (Button)e.Row.FindControl("ButtonDelete"); //access the LinkButton from the Header TemplateField using FindControl
            b.Attributes.Add("onclick", "return ConfirmOnDelete();"); //attach the JavaScript function
        }
}
 
Here’s the output when you run the page and do multiple deletion:

Print | posted on Sunday, February 22, 2009 2:01 AM |

Feedback

Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Hi, I used your coding for deletion. The control passes over all the lines and it did not display any errors. But the datas are not deleting. Can you solve the problem.
3/3/2009 9:08 PM | Karthick
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

I've used your example to help-me create my own page that update records based on wich ones have been selected. Works perfectelly!
Thank you very much!
3/10/2009 3:20 AM | Seidinger
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Helpful tutorial.
Thank in advance!
3/26/2009 8:48 PM | Nimol
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

it was a nice one
4/1/2009 5:49 PM | govind
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Thankz a lot , BOSS
4/12/2009 3:51 AM | Abul Hasan
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

thanks.. i wnt to very simple coding
4/16/2009 3:20 AM | Victor
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

thanks.. i want to very simple coding
4/16/2009 3:21 AM | Victor
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Hi Ryan,

That was an interesting questions.. I will try to create a simple demo about it soon.. For now Multiple Delete in GridView doesn't support deleting while paging..

Thanks
5/21/2009 1:06 PM | Vinz
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

so good
6/11/2009 8:46 PM | yothin
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Hi Vinz,

its very nice code and it helped me a lot....when i did the same as u said i my code was working fine. but when i tried to implement javascript to display a confirm box before deleting i m geting an error saying object reference is not set to instance of an object. when i debug the code to see where it is giving me error, i found out that before binding the data to gridview its going to RowDataBound event of the gridview and its throwing an exception saying object reference is not set to instance of an object. so what could be the reason for this error i m not able to figure it out. so kindly tell me a solution for this.
6/15/2009 9:53 AM | JAY
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Hi JAY,

Probably the FindControl method fails that's why you get the error.. When using FindControl , be sure that the control that you are trying to reference exist..
6/15/2009 9:01 PM | Vinz
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

compile time error..'System.EventArgs' does not contain a definition for 'Row'.. please help.. thanks in advance
6/30/2009 12:29 AM | azar
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

@azar,

In what line are you getting that error? Can you post it here?
6/30/2009 12:41 AM | Vinz
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Hi,

If duplicate CustomerId is entered will it delete both the record or will it delete only the selected row.

Thank you
7/30/2009 12:11 AM | Zeko
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

If there are multiple data for the selected CustomerID then I think it will be deleted all.
7/30/2009 2:27 PM | Vinz
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

Thank you very much for this article
8/27/2009 10:08 PM | sam
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

could you send me the whole source & the file to my email!!
thx man!!! btw great info and damn u are expert in this!!!
9/22/2009 6:56 PM | LoxZ
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

btw ur code did not validate the user!!
for example wad if the user nvr checked the checkbox!!!
but the javascript still come out????
9/22/2009 8:46 PM | LoxZ
Gravatar

# re: GridView Multiple Delete with CheckBox and Confirm

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
11/15/2009 4:50 PM | Hoang Le
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: