How to delete Multiple Record in Gridview in Asp.Net



Here we will Create deletion action when we delete multiple record from Gridview then from Database also we have to delete record what we delete in Gridview. For that we have to create checkbox in each row inside Gridview for delete multiple record. Here is the Code Snippets.

HTML CODE:
<div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="True"
            OnPageIndexChanging="GridView1_PageIndexChanging"
            OnPageIndexChanged="GridView1_PageIndexChanged" BackColor="White"
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
            ForeColor="Black" GridLines="Vertical">
            <AlternatingRowStyle BackColor="#CCCCCC" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="Checkbox1" runat="server" />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="Button1" runat="server" Text="DELETE" OnClick="Button1_Click" OnClientClick="return DeleteConfirmation();" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="EmpID" HeaderText="EmpID" />
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" />
                <asp:BoundField DataField="Salary" HeaderText="Salary" />
                <asp:BoundField DataField="Address" HeaderText="Address" />
            </Columns>
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
         <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
         <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView>
    </div>

For Confirmation we will create JavaScript code in design page.
<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>

CODE BEHIND:
SqlCommand cmd;
        SqlDataAdapter da;
        SqlConnection con = new SqlConnection("Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserName;Password=Password");
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                bind();
            }
        }
        public void bind()
        {
            SqlConnection con = new SqlConnection("Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserName;Password=Password");
            con.Open();

            SqlDataAdapter da = new SqlDataAdapter("select * from Employee", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();

            con.Close();
        }
private void DeleteMultipleRecords(StringCollection idCollection)
        {
            //Create sql Connection and Sql Command
            //con.Open();
            SqlCommand cmd = new SqlCommand();
            string IDs = "";

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

        protected void Button1_Click(object sender, EventArgs e)
        {
            StringCollection idCollection = new StringCollection();
            string strID = string.Empty;

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox Checkbox1 = (CheckBox)
                   GridView1.Rows[i].Cells[0].FindControl("Checkbox1");
                if (Checkbox1 != null)
                {
                    if (Checkbox1.Checked)
                    {
                        strID = GridView1.Rows[i].Cells[1].Text;
                        idCollection.Add(strID);
                    }
                }
              

            }
            DeleteMultipleRecords(idCollection);
            GridView1.DataBind();
        }

Now Check in Web browser for multiple record Deletion.


Related Posts

Previous
Next Post »

Thanks for comments.....