C#怎么单击datagridview行将表外对应的checkbox选中
时间: 2023-07-12 19:13:18 浏览: 93
可以使用 DataGridView 的 CellClick 事件来实现单击行时选中对应的 checkbox。
首先,在 DataGridView 控件的 Columns 集合中添加一个 DataGridViewCheckBoxColumn 列,用来显示 checkbox。
然后,设置这个列的 ReadOnly 属性为 false,使其可以被编辑。
接着,在 DataGridView 的 CellClick 事件中,判断点击的是不是 checkbox 列,如果是,则将对应行的 checkbox 设置为选中。
以下是示例代码:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
// 判断点击的是不是 checkbox 列
if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn &&
e.RowIndex >= 0)
{
// 将对应行的 checkbox 设置为选中
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
checkbox.Value = !(bool)checkbox.Value;
}
}
注意:如果以编辑模式单击 checkbox 列,会触发 CellClick 事件和 CellValueChanged 事件。为了避免重复执行代码,可以在 CellValueChanged 事件中添加一个判断,只在 checkbox 值改变时执行相关操作。
相关推荐


















