Use CheckBox Inside ASP.NET GridView

We will use a Checkbox inside a GridView and in that the user selects the data and that data is saved to the database.

Create a web application

Step 1. Open your Visual Studio 2010 (or newer) and create an empty website. Name it gridview_demo (or give it your own name).

Step 2. In Solution Explorer, you will see your empty website, add a web form, and a SQL Server database as in the following.

  • For Web Form: gridview_demo (your empty website) then right-click then select Add New Item -> Web Form. Name it gridview_demo.aspx.
  • For SQL Server Database: gridview_demo (your empty website) right-click then select Add New Item -> SQL Server Database. Add the database inside the App_Data_folder.

Create Database Table

Step1. In Server Explorer, click on your database (Database.mdf) then select Tables -> Add New Table. Make the table like this.

Go to your database (Database.mdf) and create a table tbl_Data. Go to the database.mdf, then Table and Add New table. Design your table like the following:

Table tbl_data (don't forget to make ID as Identity Specification - -> Yes).

ID

In a similar manner use another table and name it tbl_save, with the same field.

Save

Design the Page

Step 1. Now open your gridview_demo.aspx file to create our simple design with the GridView and a button.

Gridview_demo.aspx

<%@ 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>
    <form id="form1" runat="server">
    <p>
        
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"   
            BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"   
            CellPadding="4" ForeColor="Black" GridLines="Vertical">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("id") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("city") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Select Data">
                    <EditItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCC99" />
            <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#F7F7DE" />
            <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FBFBF2" />
            <SortedAscendingHeaderStyle BackColor="#848384" />
            <SortedDescendingCellStyle BackColor="#EAEAD3" />
            <SortedDescendingHeaderStyle BackColor="#575357" />
        </asp:GridView>
        
        <br />
        
    </p>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"   
        Text="Save to Database" />
    </form>
</body>
</html>

Your design will look like this.

 Design

Code Behind

Step 1. Open your gridview_demo.aspx.cs and write some code so that the application works.

Gridview_demo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            refreshdata();
        }
    }
    public void refreshdata()
    {
        SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvrow in GridView1.Rows)
        {
            var checkbox = gvrow.FindControl("CheckBox1") as CheckBox;
            if (checkbox.Checked)
            {
                var lblID = gvrow.FindControl("Label1") as Label;
                var lblName = gvrow.FindControl("Label2") as Label;
                var lblCity = gvrow.FindControl("Label3") as Label;
                SqlCommand cmd = new SqlCommand("insert into tbl_save (id,name,city) values (@id,@name,@city)", con);
                cmd.Parameters.AddWithValue("id", lblID.Text);
                cmd.Parameters.AddWithValue("name", lblName.Text);
                cmd.Parameters.AddWithValue("city", lblCity.Text);
                con.Open();
                int i = cmd.ExecuteNonQuery();
                con.Close();
                refreshdata();
            }
        }
    }
}

The Output

Output

After clicking the button, just check your tbl_save table. You will get your selected data saved to the database.

Table

You can use multiple selections and save them to the database, I think this is much more flexible than SQLbulk functions.

I hope you like it. Thank you for reading. Have a good day.


Similar Articles