Add check boxes column in DataGridView for deleting records from database

 

Introduction

In this article i will describe How to Add check boxes column DataGridView for deleting records from database which are selected.

History

In the Previous articles i explained how to add paging in gridview of asp.nethow to retrieve value from query string using C# and ASP.Netwhat is namespace for arraylistGet Selected RadioButton Value of RadioButtonList using C# and ASP.Net, how to create serial no. column in gridview using asp.net and many more about ASP.Net.

Step 1.

Create Table "Products" in Your Database which contains following columns :

1. ID

2. Category

3. Product_Name

4. Price

Step 2.

Copy and Paste Below Code in your .aspx page

<asp:GridView ID="gvdetails" runat="server" 
                        AutoGenerateColumns="False" CellPadding="4" Font-Bold="False" 
                        ForeColor="#333333" Width="600px">
                        <Columns>
                            <asp:TemplateField HeaderText="S No." ItemStyle-Width="40px">
                                <ItemTemplate>
                    <%#Container.DataItemIndex+1 %>
                                </ItemTemplate>
                                <ItemStyle Width="40px" />
                            </asp:TemplateField>
                           <asp:TemplateField ItemStyle-Width="20px">
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkheader" runat="server" 
                                        onclick="javascript:SelectheaderCheckboxes(this)" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkchild" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="40">
                                <ItemStyle Width="40px" />
                            </asp:BoundField>
                            <asp:BoundField DataField="category" HeaderText="Category" />
                            <asp:BoundField DataField="product_name" HeaderText="Product Name" />
                            <asp:BoundField DataField="price" HeaderText="Price" ItemStyle-Width="40">
                                <ItemStyle Width="40px" />
                            </asp:BoundField>
                            
                           
                        </Columns>
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <HeaderStyle BackColor="#CCCCCC" Font-Bold="True" ForeColor="Gray" />
                        <EditRowStyle BackColor="#999999" />
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    </asp:GridView>

Step 3.

Add Below Script on Head Section of your .aspx page.

<script type="text/javascript">

// Select/Deselect checkboxes based on header checkbox

function SelectheaderCheckboxes(headerchk) 
{

 

var gvcheck = document.getElementById('gvdetails');

var i;

//Condition to check header checkbox selected or not if that is true checked all checkboxes

if (headerchk.checked) {

for (i = 0; i < gvcheck.rows.length; i++) {

var inputs = gvcheck.rows[i].getElementsByTagName('input');

inputs[0].checked = true;

}

}

//if condition fails uncheck all checkboxes in gridview

else {

for (i = 0; i < gvcheck.rows.length; i++) {

var inputs = gvcheck.rows[i].getElementsByTagName('input');

inputs[0].checked = false;

}

}

}

//function to check header checkbox based on child checkboxes condition

function Selectchildcheckboxes(header) {

var ck = header;

var count = 0;

var gvcheck = document.getElementById('gvdetails');

var headerchk = document.getElementById(header);

var rowcount = gvcheck.rows.length;

//By using this for loop we will count how many checkboxes has checked

for (i = 1; i < gvcheck.rows.length; i++) {

var inputs = gvcheck.rows[i].getElementsByTagName('input');

if (inputs[0].checked) {

count++;

}

}

//Condition to check all the checkboxes selected or not

if (count == rowcount-1) {

headerchk.checked = true;

}

else {

headerchk.checked = false;

}

}

 </script>

Step 4.

Add Below Code on Load Event of your page :

  string dbstring = ConfigurationManager.ConnectionStrings["database_con"].ConnectionString;
        SqlConnection connection = new SqlConnection(dbstring);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Products", connection);
        DataSet ds = new DataSet();
        ad.Fill(ds);
        gvdetails.DataSource = ds;
        gvdetails.DataBind();

Step 5.

Drag and Drop Button Control on your .aspx page and write below code on click event of the Button. Also Set "Text" Property of Button to "Delete". This Button is For Deleting Selected Records from database.

 foreach (GridViewRow row in gvdetails.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkDelete = (CheckBox)row.Cells[0].FindControl("chkchild");

                if (chkDelete != null)
                {
                    if (chkDelete.Checked)
                    {
                        string id = row.Cells[2].Text;
                        string dbstring = ConfigurationManager.ConnectionStrings["database_con"].ConnectionString;
                        SqlConnection connection = new SqlConnection(dbstring);
                        connection.Open();
                        SqlCommand comm = new SqlCommand("delete from products where id='" + id + "'", connection);
                        comm.ExecuteNonQuery();
                        Label1.Visible = true;
                        Label1.ForeColor = System.Drawing.Color.Green;
                        Label1.Text = "Successfully Deleted";
                       
                        connection.Close();


                    }

                }
            }

        }

Step 6.

Now Run Your Application. And you can see CheckBoxes Column In your DataGridView.

Screenshot.

Step 7.

Select Records using CheckBox. And Hit "Delete" Button. And You can see the selected records will be Deleted From Database.

Give your Valuable Comments.
comments powered by Disqus
 
Follow me on twitter
About Me
Harpreet Singh
I began programming with C++ when i was 17. Then at the middle of my study .NET came. Then I began to read C# and VB.NET. By the time i learnt SQL and ASP.NET, and developed some websites such as news portals that are active now. Currently i am running my own Software company.
More Articles