Deleting Multiple Records From Gridview Using ASP.Net C#

Background

There is often a need to delete one or more records from a GridView, so by considering this requirement I have decided to write this article. Now before creating the application, let us create a table named employee in a database from which we show the records in a GridView, the table has the following fields (shown in the following image):
 
 
I hope you have created the same type of table.
 
Now create the project as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Give the project the name "DeletingMultiRec" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer then seelct "Add New Item" - "Default.aspx" page.
  5. Add one button, one label and a GridView.

Default.aspx source code.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body bgcolor="silver">  
  9.     <form id="form1" runat="server">  
  10.     <br />  
  11.     <h2 style="color: #808000; font-size: x-large; font-weight: bolder;">  
  12.         Article by Vithal Wadje</h2>  
  13.     <br />  
  14.     <div>  
  15.         <asp:GridView ID="GrdEmpDetails" runat="server" AutoGenerateColumns="False" Font-Names="Arial"  
  16.             Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="green"  
  17.             AllowPaging="True" OnPageIndexChanging="OnPaging" DataKeyNames="Id" CellPadding="4"  
  18.             ForeColor="#333333" GridLines="None">  
  19.             <Columns>  
  20.                 <asp:TemplateField>  
  21.                     <HeaderTemplate>  
  22.                         <asp:Label runat="server" Text="Delete All "></asp:Label>  
  23.                         <asp:CheckBox ID="chkAll" runat="server" onclick="checkAll(this);" />  
  24.                     </HeaderTemplate>  
  25.                     <ItemTemplate>  
  26.                         <asp:CheckBox ID="chk" runat="server" onclick="Check_Click(this)" />  
  27.                     </ItemTemplate>  
  28.                 </asp:TemplateField>  
  29.                 <asp:BoundField ItemStyle-Width="150px" DataField="Name" HeaderText=" Name">  
  30.                     <ItemStyle Width="150px"></ItemStyle>  
  31.                 </asp:BoundField>  
  32.                 <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City">  
  33.                     <ItemStyle Width="150px"></ItemStyle>  
  34.                 </asp:BoundField>  
  35.                 <asp:BoundField ItemStyle-Width="150px" DataField="Address" HeaderText="Address">  
  36.                     <ItemStyle Width="150px"></ItemStyle>  
  37.                 </asp:BoundField>  
  38.                 <asp:BoundField ItemStyle-Width="150px" DataField="Designation" HeaderText="Designation">  
  39.                     <ItemStyle Width="150px"></ItemStyle>  
  40.                 </asp:BoundField>  
  41.             </Columns>  
  42.             <AlternatingRowStyle BackColor="White" />  
  43.             <EditRowStyle BackColor="#7C6F57" />  
  44.             <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  45.             <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"></HeaderStyle>  
  46.             <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
  47.             <RowStyle BackColor="#E3EAEB" />  
  48.             <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
  49.             <SortedAscendingCellStyle BackColor="#F8FAFA" />  
  50.             <SortedAscendingHeaderStyle BackColor="#246B61" />  
  51.             <SortedDescendingCellStyle BackColor="#D4DFE1" />  
  52.             <SortedDescendingHeaderStyle BackColor="#15524A" />  
  53.         </asp:GridView>  
  54.         <asp:HiddenField ID="hdncnt" runat="server" Value="0" />  
  55.         <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return ConfirmDelete();"  
  56.             OnClick="btnDelete_Click" />  
  57.     </div>  
  58.     </form>  
  59. </body>  
  60. </html> 
Now, create the following function in the default.aspx.cs page to bind the GridView:
  1. private void BindGrid()    
  2. {  
  3.     connection();  
  4.     string query = "select * from Employee";  
  5.     SqlDataAdapter da = new SqlDataAdapter(query, con);  
  6.     DataTable dt = new DataTable();  
  7.     da.Fill(dt);  
  8.     GrdEmpDetails.DataSource = dt;  
  9.     GrdEmpDetails.DataBind();  
  10. }
Now write the following function for deleting records:
  1. private void DeleteRecord(string SelectedId)    
  2. {    
  3.     connection();    
  4.     query = "delete from Employee " + "where Id=@Id";    
  5.     com = new SqlCommand(query, con);    
  6.     com.Parameters.AddWithValue("@Id", SelectedId);    
  7.     com.ExecuteNonQuery();    
  8.     con.Close();    
  9. } 
Create the following function for selecting one or more records:
  1. private void SelectRecords()    
  2. {    
  3.     int currentSelectedRec = 0;  
  4.     CheckBox chkAll = (CheckBox)GrdEmpDetails.HeaderRow.Cells[0].FindControl("chkAll");    
  5.     chkAll.Checked = true;  
  6.     ArrayList arr = (ArrayList)ViewState["RecordsTobeDeleted"];  
  7.     for (int i = 0; i < GrdEmpDetails.Rows.Count; i++)    
  8.     {  
  9.         CheckBox chk = (CheckBox)GrdEmpDetails.Rows[i].Cells[0].FindControl("chk");  
  10.         if (chk != null)    
  11.         {    
  12.             chk.Checked = arr.Contains(GrdEmpDetails.DataKeys[i].Value);    
  13.   
  14.             if (!chk.Checked)    
  15.             {    
  16.                 chkAll.Checked = false;    
  17.             }  
  18.             else    
  19.             {     
  20.                 currentSelectedRec++;    
  21.             }    
  22.         }  
  23.     }    
  24.     hdncnt.Value = (arr.Count - currentSelectedRec).ToString();    
  25. } 
Now write the following code for the button delete click:
  1. protected void btnDelete_Click(object sender, EventArgs e)    
  2. {    
  3.     int count = 0;    
  4.     SelectRecords();    
  5.     GrdEmpDetails.AllowPaging = false;    
  6.     GrdEmpDetails.DataBind();    
  7.     ArrayList arr = (ArrayList)ViewState["RecordsTobeDeleted"];    
  8.     count = arr.Count;    
  9.     for (int i = 0; i < GrdEmpDetails.Rows.Count; i++)    
  10.     {  
  11.         if (arr.Contains(GrdEmpDetails.DataKeys[i].Value))    
  12.         {  
  13.             DeleteRecord(GrdEmpDetails.DataKeys[i].Value.ToString());  
  14.             arr.Remove(GrdEmpDetails.DataKeys[i].Value);  
  15.         }  
  16.     }    
  17.     ViewState["RecordsTobeDeleted"] = arr;    
  18.     hdncnt.Value = "0";    
  19.     GrdEmpDetails.AllowPaging = true;    
  20.     BindGrid();    
  21.     alertmsg(count);  
  22. } 
Now the combined code of all the above will look like:
  1. using System;    
  2. using System.Web.UI.WebControls;    
  3. using System.Configuration;    
  4. using System.Data;    
  5. using System.Data.SqlClient;    
  6. using System.Text;    
  7. using System.Collections;    
  8.     
  9. public partial class _Default : System.Web.UI.Page    
  10. {    
  11.     private SqlConnection con;    
  12.     private SqlCommand com;    
  13.     private string constr, query;    
  14.     private void connection()    
  15.     {    
  16.         constr = ConfigurationManager.ConnectionStrings["ConnMultiRec"].ToString();    
  17.         con = new SqlConnection(constr);    
  18.         con.Open();  
  19.     }   
  20.     protected void Page_Load(object sender, EventArgs e)    
  21.     {    
  22.         if (IsPostBack == true)    
  23.         {    
  24.             GetData();  
  25.         }    
  26.         BindGrid();  
  27.     }  
  28.     private void BindGrid()    
  29.     {    
  30.         connection();    
  31.         string query = "select * from Employee";    
  32.         SqlDataAdapter da = new SqlDataAdapter(query, con);    
  33.         DataTable dt = new DataTable();    
  34.         da.Fill(dt);    
  35.         GrdEmpDetails.DataSource = dt;    
  36.         GrdEmpDetails.DataBind();  
  37.     }    
  38.     private void GetData()    
  39.     {    
  40.         ArrayList arr;  
  41.         if (ViewState["RecordsTobeDeleted"] != null)    
  42.         {    
  43.             arr = (ArrayList)ViewState["RecordsTobeDeleted"];    
  44.         }    
  45.         else    
  46.         {    
  47.             arr = new ArrayList();    
  48.         }   
  49.         CheckBox chkAll = (CheckBox)GrdEmpDetails.HeaderRow.Cells[0].FindControl("chkAll");    
  50.         for (int i = 0; i < GrdEmpDetails.Rows.Count; i++)    
  51.         {  
  52.             if (chkAll.Checked)    
  53.             {  
  54.                 if (!arr.Contains(GrdEmpDetails.DataKeys[i].Value))    
  55.                 {  
  56.                     arr.Add(GrdEmpDetails.DataKeys[i].Value);  
  57.                 }  
  58.             }  
  59.             else    
  60.             {  
  61.                 CheckBox chk = (CheckBox)GrdEmpDetails.Rows[i]    
  62.                                    .Cells[0].FindControl("chk");    
  63.                 if (chk.Checked)    
  64.                 {  
  65.                     if (!arr.Contains(GrdEmpDetails.DataKeys[i].Value))    
  66.                     {  
  67.                         arr.Add(GrdEmpDetails.DataKeys[i].Value);  
  68.                     }  
  69.                 }   
  70.                 else    
  71.                 {  
  72.                     if (arr.Contains(GrdEmpDetails.DataKeys[i].Value))    
  73.                     {  
  74.                         arr.Remove(GrdEmpDetails.DataKeys[i].Value);  
  75.                     }  
  76.                 }   
  77.             }   
  78.         }    
  79.         ViewState["RecordsTobeDeleted"] = arr;  
  80.     }   
  81.     private void SelectRecords()    
  82.     {    
  83.         int currentSelectedRec = 0;  
  84.         CheckBox chkAll = (CheckBox)GrdEmpDetails.HeaderRow.Cells[0].FindControl("chkAll");    
  85.         chkAll.Checked = true;  
  86.         ArrayList arr = (ArrayList)ViewState["RecordsTobeDeleted"];  
  87.         for (int i = 0; i < GrdEmpDetails.Rows.Count; i++)    
  88.         {  
  89.             CheckBox chk = (CheckBox)GrdEmpDetails.Rows[i].Cells[0].FindControl("chk");  
  90.             if (chk != null)    
  91.             {    
  92.                 chk.Checked = arr.Contains(GrdEmpDetails.DataKeys[i].Value);  
  93.                 if (!chk.Checked)    
  94.                 {    
  95.                     chkAll.Checked = false;    
  96.                 }  
  97.                 else    
  98.                 {  
  99.                     currentSelectedRec++;  
  100.                 }   
  101.             }  
  102.         }    
  103.         hdncnt.Value = (arr.Count - currentSelectedRec).ToString();    
  104.     }  
  105.     protected void OnPaging(object sender, GridViewPageEventArgs e)    
  106.     {    
  107.         GrdEmpDetails.PageIndex = e.NewPageIndex;    
  108.         GrdEmpDetails.DataBind();    
  109.         SelectRecords();    
  110.     }  
  111.     protected void btnDelete_Click(object sender, EventArgs e)    
  112.     {    
  113.         int count = 0;    
  114.         SelectRecords();    
  115.         GrdEmpDetails.AllowPaging = false;    
  116.         GrdEmpDetails.DataBind();    
  117.         ArrayList arr = (ArrayList)ViewState["RecordsTobeDeleted"];    
  118.         count = arr.Count;    
  119.         for (int i = 0; i < GrdEmpDetails.Rows.Count; i++)    
  120.         {  
  121.             if (arr.Contains(GrdEmpDetails.DataKeys[i].Value))    
  122.             {  
  123.                 DeleteRecord(GrdEmpDetails.DataKeys[i].Value.ToString());  
  124.                 arr.Remove(GrdEmpDetails.DataKeys[i].Value);  
  125.             }  
  126.         }  
  127.         ViewState["RecordsTobeDeleted"] = arr;    
  128.         hdncnt.Value = "0";    
  129.         GrdEmpDetails.AllowPaging = true;    
  130.         BindGrid();    
  131.         alertmsg(count);    
  132.     }  
  133.     private void DeleteRecord(string SelectedId)    
  134.     {  
  135.         connection();    
  136.         query = "delete from Employee " + "where Id=@Id";    
  137.         com = new SqlCommand(query, con);    
  138.         com.Parameters.AddWithValue("@Id", SelectedId);    
  139.         com.ExecuteNonQuery();    
  140.         con.Close();    
  141.     }    
  142.     private void alertmsg(int SelectedReccount)    
  143.     {    
  144.         StringBuilder sb = new StringBuilder();    
  145.         sb.Append("<script type = 'text/javascript'>");    
  146.         sb.Append("alert('");    
  147.         sb.Append(SelectedReccount.ToString() + "  " + "   ");    
  148.         sb.Append("Records are  deleted.');");    
  149.         sb.Append("</script>");    
  150.         ClientScript.RegisterStartupScript(this.GetType(), "script", sb.ToString());    
  151.     }    
  152. } 
Now run the application; the UI will look like as in the following:
 
 
 
Now select some records and click on the delete button, after deleting records the following message is shown.
 
 
 
Now from all the preceding examples, we have learned how to delete one or more records from a GridView. I hope you have enjoyed this article while coding.
 
Note:
  • For detailed code please download the Zip file attached above.
  • Don't forget to create the text file for storing votes.
Summary
 
I hope this article is useful. If you have any suggestion regarding this article then please contact me.