We can add checkbox to datagridview by using DataGridViewCheckBoxColumn in C#. This checkbox behaves same as normal checkbox in C#. But we don't have Checkbox state changed event to handle for datagridview checkbox. In this article we discuss about how to add checkbox column to the datagridview and how to handle checkbox changed event for datagridview.
We can add checkbox column to datagridview by creating object for DataGridViewCheckBoxColumn class. And we can handle checkbox state changed event by using CellValueChanged event of datagridview as shown below.
using System;
using System.Data;
using System.Windows.Forms;
namespace CSharpDataGridviewCheckbox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
for (int i = 1; i < 6; i++)
{
DataRow dr = dt.NewRow();
dr["Id"] = i;
dr["Name"] = "A" + i.ToString();
dt.Rows.Add(dr);
}
DataGridViewCheckBoxColumn dgCheckBox = new DataGridViewCheckBoxColumn();
dgCheckBox.DisplayIndex = 0;
dgCheckBox.Width = 50;
dataGridView1.Columns.Add(dgCheckBox);
dataGridView1.DataSource = dt;
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
}
}
As shown above we add the checkbox to the datagridview by using DataGridViewCheckBoxColumn class and we display the checkbox status by using datagridview CellValueChanged event of datagridview.
Now run the application and output displays as shown below.