In this article I will explain with an example, how to populate (bind) CheckBox in GridView from database in ASP.Net using C# and VB.Net.
This article also explains how to save the CheckBox checked (selected) values to database in ASP.Net using C# and VB.Net.
Database
I have made use of the following table Hobbies with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The following HTML Markup consists of an ASP.Net GridView with a TemplateField and one BoundField column.
The TemplateField column consists of a CheckBox. The Checked property 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.
Below the GridView, there is a Button for saving checked (selected) CheckBox values to database.
The DateKeyNames property has been set for GridView to store the Primary Key which will be 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="Description" HeaderText="Hobby" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Binding the GridView
Inside the Page Load event 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.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT [HobbyId], [Description], [IsSelected] FROM Hobbies")
Using sda As New SqlDataAdapter()
cmd.Connection = 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
End Sub
Updating the CheckBox values to Database
When the Save Button is clicked, a loop is executed over the GridView rows 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.Connection = con;
con.Open();
foreach (GridViewRow row in GridView1.Rows)
{
//Get the HobbyId from the DataKey property.
int hobbyId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
//Get the checked value of the CheckBox.
bool isSelected = (row.FindControl("chkSelect") as CheckBox).Checked;
//Save to database.
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@HobbyId", hobbyId);
cmd.Parameters.AddWithValue("@IsSelected", isSelected);
cmd.ExecuteNonQuery();
}
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
VB.Net
Protected Sub Save(sender As Object, e As EventArgs)
Dim constr As 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()
For Each row As GridViewRow In GridView1.Rows
'Get 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
'Save to database.
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("@HobbyId", hobbyId)
cmd.Parameters.AddWithValue("@IsSelected", isSelected)
cmd.ExecuteNonQuery()
Next
con.Close()
Response.Redirect(Request.Url.AbsoluteUri)
End Using
End Using
End Sub
Screenshot
Demo
Downloads