DataGridView中DataGridViewCheckBoxColumns各种使用

时间:2021-03-20 17:27:56

一、CheckBox选定方式

事件:单击单元格内容时发生

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//第一种Checkbox选定方式可行
if ((bool)dataGridView1.Rows[e.RowIndex].Cells[1].Selected == true)
{

}

//第二种Checkbox选定方式可行
if ((bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue == true)
{
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
if (e.ColumnIndex == i)
{

}
}
}
}

二、CheackBox自动选定(打勾)

首先把DataGridViewCheckBoxColumns中的:
FalseValue = 0
TrueValue = 1;

然后声明一个:
DataGridViewCell Checkbox = (DataGridViewCell)this.datagridview1.Rows[0].Cells[0];

最后用一个循环遍历所有需要打勾的列:

DataGridViewCell Checkbox = (DataGridViewCell)this.datagridview1.Rows[0].Cells[0];
Checkbox.Value = 1;

注:在自定义控件中需要绘制完所有的单元格后执行。
执行事件:private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)