Here is an example on CodeProject, it is a bit verbose, but it shows how to use checkboxes in a datagridview:
DataGridView Helper Class[
^]
Here is a simpler example, you can skip the lines using the .png images:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace TestForm1
{
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
}
private void buttonFill_Click(object sender, EventArgs e)
{
myDataGridView.Columns.Clear();
myDataGridView.RowHeadersVisible = false;
myDataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke;
myDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataGridViewImageColumn dgvButton = new DataGridViewImageColumn();
dgvButton.Name = "";
var image1 = Image.FromFile("expand.png");
dgvButton.Image = image1;
myDataGridView.Columns.Add(dgvButton);
DataGridViewTextBoxColumn dgvText = new DataGridViewTextBoxColumn();
dgvText.Name = "User ID";
myDataGridView.Columns.Add(dgvText);
DataGridViewTextBoxColumn dgvText2 = new DataGridViewTextBoxColumn();
dgvText2.Name = "Password";
myDataGridView.Columns.Add(dgvText2);
DataGridViewComboBoxColumn dgvCombo = new DataGridViewComboBoxColumn();
dgvCombo.Name = "Priority";
dgvCombo.Width = 300;
dgvCombo.DataSource = new string[] { "One", "Two", "Three" };
myDataGridView.Columns.Add(dgvCombo);
DataGridViewCheckBoxColumn dgvCheck = new DataGridViewCheckBoxColumn(true);
myDataGridView.Columns.Add(dgvCheck);
var row = new object[] { image1, "abc", "xyz", "One", false };
myDataGridView.Rows.Add(row);
row = new object[] { image1, "pqr", "stu", "Two", true };
myDataGridView.Rows.Add(row);
row = new object[] { image1, "gaga", "aha", "Three", false };
myDataGridView.Rows.Add(row);
row = new object[] { image1, "zuzu", "lala", "One", false };
myDataGridView.Rows.Add(row);
}
private void myDataGridView_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
var imageName = myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag ?? "expand.png";
if (imageName.ToString() == "toggle.png")
{
imageName = "expand.png";
}
else
{
imageName = "toggle.png";
}
myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Image.FromFile(imageName.ToString());
myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag = imageName;
string str = myDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
MessageBox.Show("You Have Selected " + str);
}
}
private void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1)
{
if (myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == "abc")
{
e.CellStyle.ForeColor = Color.Gray;
}
}
if (e.ColumnIndex == 4)
{
var check = myDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (check != null && (bool)check == false)
{
e.CellStyle.BackColor = Color.Gray;
e.CellStyle.ForeColor = Color.Red;
}
}
}
}
}