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.
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: