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:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
- Give the project the name "DeletingMultiRec" or another as you wish and specify the location.
- Then right-click on Solution Explorer then seelct "Add New Item" - "Default.aspx" page.
- Add one button, one label and a GridView.
Default.aspx source code.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body bgcolor="silver">
- <form id="form1" runat="server">
- <br />
- <h2 style="color: #808000; font-size: x-large; font-weight: bolder;">
- Article by Vithal Wadje</h2>
- <br />
- <div>
- <asp:GridView ID="GrdEmpDetails" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
- Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="green"
- AllowPaging="True" OnPageIndexChanging="OnPaging" DataKeyNames="Id" CellPadding="4"
- ForeColor="#333333" GridLines="None">
- <Columns>
- <asp:TemplateField>
- <HeaderTemplate>
- <asp:Label runat="server" Text="Delete All "></asp:Label>
- <asp:CheckBox ID="chkAll" runat="server" onclick="checkAll(this);" />
- </HeaderTemplate>
- <ItemTemplate>
- <asp:CheckBox ID="chk" runat="server" onclick="Check_Click(this)" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:BoundField ItemStyle-Width="150px" DataField="Name" HeaderText=" Name">
- <ItemStyle Width="150px"></ItemStyle>
- </asp:BoundField>
- <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City">
- <ItemStyle Width="150px"></ItemStyle>
- </asp:BoundField>
- <asp:BoundField ItemStyle-Width="150px" DataField="Address" HeaderText="Address">
- <ItemStyle Width="150px"></ItemStyle>
- </asp:BoundField>
- <asp:BoundField ItemStyle-Width="150px" DataField="Designation" HeaderText="Designation">
- <ItemStyle Width="150px"></ItemStyle>
- </asp:BoundField>
- </Columns>
- <AlternatingRowStyle BackColor="White" />
- <EditRowStyle BackColor="#7C6F57" />
- <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
- <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"></HeaderStyle>
- <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
- <RowStyle BackColor="#E3EAEB" />
- <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
- <SortedAscendingCellStyle BackColor="#F8FAFA" />
- <SortedAscendingHeaderStyle BackColor="#246B61" />
- <SortedDescendingCellStyle BackColor="#D4DFE1" />
- <SortedDescendingHeaderStyle BackColor="#15524A" />
- </asp:GridView>
- <asp:HiddenField ID="hdncnt" runat="server" Value="0" />
- <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return ConfirmDelete();"
- OnClick="btnDelete_Click" />
- </div>
- </form>
- </body>
- </html>
Now, create the following function in the default.aspx.cs page to bind the GridView:
- private void BindGrid()
- {
- connection();
- string query = "select * from Employee";
- SqlDataAdapter da = new SqlDataAdapter(query, con);
- DataTable dt = new DataTable();
- da.Fill(dt);
- GrdEmpDetails.DataSource = dt;
- GrdEmpDetails.DataBind();
- }
Now write the following function for deleting records:
- private void DeleteRecord(string SelectedId)
- {
- connection();
- query = "delete from Employee " + "where Id=@Id";
- com = new SqlCommand(query, con);
- com.Parameters.AddWithValue("@Id", SelectedId);
- com.ExecuteNonQuery();
- con.Close();
- }
Create the following function for selecting one or more records:
- private void SelectRecords()
- {
- int currentSelectedRec = 0;
- CheckBox chkAll = (CheckBox)GrdEmpDetails.HeaderRow.Cells[0].FindControl("chkAll");
- chkAll.Checked = true;
- ArrayList arr = (ArrayList)ViewState["RecordsTobeDeleted"];
- for (int i = 0; i < GrdEmpDetails.Rows.Count; i++)
- {
- CheckBox chk = (CheckBox)GrdEmpDetails.Rows[i].Cells[0].FindControl("chk");
- if (chk != null)
- {
- chk.Checked = arr.Contains(GrdEmpDetails.DataKeys[i].Value);
-
- if (!chk.Checked)
- {
- chkAll.Checked = false;
- }
- else
- {
- currentSelectedRec++;
- }
- }
- }
- hdncnt.Value = (arr.Count - currentSelectedRec).ToString();
- }
Now write the following code for the button delete click:
- protected void btnDelete_Click(object sender, EventArgs e)
- {
- int count = 0;
- SelectRecords();
- GrdEmpDetails.AllowPaging = false;
- GrdEmpDetails.DataBind();
- ArrayList arr = (ArrayList)ViewState["RecordsTobeDeleted"];
- count = arr.Count;
- for (int i = 0; i < GrdEmpDetails.Rows.Count; i++)
- {
- if (arr.Contains(GrdEmpDetails.DataKeys[i].Value))
- {
- DeleteRecord(GrdEmpDetails.DataKeys[i].Value.ToString());
- arr.Remove(GrdEmpDetails.DataKeys[i].Value);
- }
- }
- ViewState["RecordsTobeDeleted"] = arr;
- hdncnt.Value = "0";
- GrdEmpDetails.AllowPaging = true;
- BindGrid();
- alertmsg(count);
- }
Now the combined code of all the above will look like:
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.