In this article I will explain with an example, how to use and get value of CheckBoxField in GridView in ASP.Net with C# and VB.Net.
CheckBoxField is by default disabled (ReadOnly) and can be modified only when the GridView Row is in Edit mode.
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 HTML Markup consists of an ASP.Net GridView with multiple event handlers assigned which will be discussed later.
The GridView has a CommandField column which will display the command buttons i.e. Edit, Update, Cancel and Delete.
The first column in the GridView is a CheckBoxField which is bound to a Boolean or BIT column.
Note: You can only bind a Boolean or BIT Column to a CheckBoxField.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId"
OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelEdit" OnRowUpdating="OnRowUpdating">
<Columns>
<asp:CheckBoxField DataField="IsSelected" />
<asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" ReadOnly="true" />
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Populating the GridView control
The GridView is populated from the database inside the Page Load event of the page.
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], [Hobby], [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], [Hobby], [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
GridView OnRowEditing and OnRowCancelEdit events
Edit
When the Edit Button is clicked, the GridView’s OnRowEditing event handler is triggered. Here simply the EditIndex of the GridView is updated with the Row Index of the GridView Row to be edited.
Cancel Edit
When the Cancel Button is clicked, the GridView’s OnRowCancelEdit event handler is triggered. Here the EditIndex is set to -1 and the GridView is populated with data.
C#
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnRowCancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Protected Sub OnRowCancelEdit(sender As Object, e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
Getting value from CheckBoxField and updating database
When the Update Button is clicked, the GridView’s OnRowUpdating event handler is triggered.
A loop is executed on the GridView rows and the HobbyId is fetched from the DataKey property of the GridView.
The CheckBoxField values are fetched by accessing the CheckBoxField column using its Index and then accessing its first Control which is a CheckBox control.
The fetched values are used to update the record in the database table.
C#
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Get the GridView Row.
GridViewRow row = GridView1.Rows[e.RowIndex];
//Get the HobbyId from the DataKey property.
int hobbyId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
//Get the checked value of the CheckBoxField column.
bool isSelected = (row.Cells[0].Controls[0] as CheckBox).Checked;
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();
cmd.Parameters.AddWithValue("@HobbyId", hobbyId);
cmd.Parameters.AddWithValue("@IsSelected", isSelected);
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
'Get the GridView Row.
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
'Get the HobbyId from the DataKey property.
Dim hobbyId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
'Get the checked value of the CheckBoxField column.
Dim isSelected As Boolean = TryCast(row.Cells(0).Controls(0), CheckBox).Checked
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()
cmd.Parameters.AddWithValue("@HobbyId", hobbyId)
cmd.Parameters.AddWithValue("@IsSelected", isSelected)
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
Demo
Downloads