In this article I will explain with an instance, how to populate (demark) CheckBox in GridView from database in ASP.Net using C# and VB.Net.

This article too explains how to save the CheckBox checked (selected) values to database in ASP.Cyberspace using C# and VB.Net.

Database

I have fabricated use of the following table Hobbies with the schema as follows.

Populate (bind) CheckBox in GridView from database in ASP.Net using C# and VB.Net

I accept already inserted few records in the table.

Populate (bind) CheckBox in GridView from database in ASP.Net using C# and VB.Net

Note : You can download the database table SQL by clicking the download link below.

HTML Markup

The following HTML Markup consists of an ASP.Cyberspace GridView with a TemplateField and ane BoundField column.

The TemplateField column consists of a CheckBox. The Checked holding of the CheckBox is bound to the IsSelected column which is of BIT data type and hence when the value saved is TRUE the CheckBox will be selected and vice versa.

Beneath the GridView, in that location is a Button for saving checked (selected) CheckBox values to database.

The DateKeyNames property has been set for GridView to store the Main Cardinal which will exist later used to update the records in database.

< asp : GridView ID ="GridView1" runat ="server" AutoGenerateColumns ="false" DataKeyNames ="HobbyId">

    < Columns >

< asp : TemplateField >

< ItemTemplate >

< asp : CheckBox ID ="chkSelect" runat ="server" Checked =' <% # Eval("IsSelected") %> ' />

</ ItemTemplate >

</ asp : TemplateField >

< asp : BoundField DataField ="Clarification" HeaderText ="Hobby" ItemStyle-Width ="150px" />

    </ Columns >

</ asp : GridView >

< br />

< asp : Button ID ="btnSave" runat ="server" Text ="Save" OnClick ="Salvage" />

Namespaces

You will demand to import the following namespaces.

C#

using Arrangement.Information;

using Arrangement.Configuration;

using System.Data.SqlClient;

VB.Net

Imports System.Data

Imports Arrangement.Configuration

Imports System.Data.SqlClient

Binding the GridView

Inside the Page Load issue handler, the GridView is populated with the records from the Hobbies table.

C#

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

    {

this.BindGrid();

    }

}

private void BindGrid()

{

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlConnection con = new SqlConnection(constr))

    {

using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Description], [IsSelected] FROM Hobbies"))

        {

using (SqlDataAdapter sda = new SqlDataAdapter())

            {

                cmd.Connection = con;

                sda.SelectCommand = cmd;

using (DataTable dt = new DataTable())

                {

                    sda.Fill(dt);

                    GridView1.DataSource = dt;

                    GridView1.DataBind();

                }

            }

        }

    }

}

VB.Cyberspace

Protected Sub Page_Load(sender As Object, e Equally EventArgs) Handles Me.Load

If Not IsPostBack Then

Me.BindGrid()

End If

Stop Sub

Private Sub BindGrid()

Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

Using con Every bit New SqlConnection(constr)

Using cmd As New SqlCommand("SELECT [HobbyId], [Description], [IsSelected] FROM Hobbies")

Using sda As New SqlDataAdapter()

                cmd.Connectedness = con

                sda.SelectCommand = cmd

Using dt As New DataTable()

                    sda.Fill(dt)

                    GridView1.DataSource = dt

                    GridView1.DataBind()

End Using

End Using

End Using

End Using

Finish Sub

Updating the CheckBox values to Database

When the Save Button is clicked, a loop is executed over the GridView rows and and then the HobbyId from the DataKeys and the CheckBox values are fetched.

The fetched values are used to update the record in the database table.

Finally, the page is redirected to itself to refresh the GridView with the updated values.

C#

protected void Save(object sender, EventArgs e)

{

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlConnection con = new SqlConnection(constr))

    {

using (SqlCommand cmd = new SqlCommand())

        {

            cmd.CommandText = "UPDATE Hobbies Set [IsSelected] = @IsSelected WHERE HobbyId=@HobbyId";

            cmd.Connectedness = con;

            con.Open up();

foreach (GridViewRow row in GridView1.Rows)

            {

//Get the HobbyId from the DataKey property.

int hobbyId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);

//Go the checked value of the CheckBox.

bool isSelected = (row.FindControl("chkSelect") equally CheckBox).Checked;

//Salve to database.

                cmd.Parameters.Articulate();

                cmd.Parameters.AddWithValue("@HobbyId", hobbyId);

                cmd.Parameters.AddWithValue("@IsSelected", isSelected);

                cmd.ExecuteNonQuery();

            }

            con.Shut();

            Response.Redirect(Asking.Url.AbsoluteUri);

        }

    }

}

VB.Net

Protected Sub Salvage(sender As Object, e As EventArgs)

Dim constr Equally String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

Using con As New SqlConnection(constr)

Using cmd As New SqlCommand()

            cmd.CommandText = "UPDATE Hobbies SET [IsSelected] = @IsSelected WHERE HobbyId=@HobbyId"

            cmd.Connection = con

            con.Open up()

For Each row As GridViewRow In GridView1.Rows

'Become the HobbyId from the DataKey property.

Dim hobbyId As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Values(0))

'Get the checked value of the CheckBox.

Dim isSelected As Boolean = TryCast(row.FindControl("chkSelect"), CheckBox).Checked

'Salve to database.

                cmd.Parameters.Clear()

                cmd.Parameters.AddWithValue("@HobbyId", hobbyId)

                cmd.Parameters.AddWithValue("@IsSelected", isSelected)

                cmd.ExecuteNonQuery()

Adjacent

            con.Close()

            Response.Redirect(Request.Url.AbsoluteUri)

End Using

End Using

End Sub

Screenshot

Populate (bind) CheckBox in GridView from database in ASP.Net using C# and VB.Net

Demo

Downloads