检测DataGridView checkbox是否被选中、勾选
在绑定DataGridView控件的CellContentClick事件中作判断
重点属性是使用EditedFormattedValue
属性
检测是否是DataGridView中button按钮被点击
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// 检测是否是button按钮被点击,使用列名称等于Delete判断
if (dataGridView1.Columns[e.ColumnIndex].Name == "Delete")
{
dataGridView1.Rows.RemoveAt(e.RowIndex);
}
// 检测是否是checkbox列,使用列名称等于select判断
if (dataGridView1.Columns[e.ColumnIndex].Name == "select")
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["select"];
// or
// DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells[0];
if ((bool)chk.EditedFormattedValue)
{
Console.WriteLine("is checked");
}
else
{
Console.WriteLine("is unchecked");
}
}
}
读取DataGridView checkbox被选中、勾选的列索引值
private void btn_update_selected_Click(object sender, EventArgs e)
{
DataGridViewSelectedRowCollection dataGridViewSelectedRowCollection = dataGridView1.SelectedRows;
DataGridViewRowCollection rowCollection = dataGridView1.Rows;
for(int i = 0; i < rowCollection.Count; i++) {
if ((bool)rowCollection[i].Cells[0].EditedFormattedValue) {
Console.WriteLine("选中的列index:" + i);
}
}
}