感谢 KeithS 提供的有用答案。
当我查看CellValueChanged的文档时,我发现这很有帮助:
DataGridView.CellValueChanged 事件在提交用户指定的值时发生,这通常在焦点离开单元格时发生。
但是,对于复选框单元格,您通常希望立即处理更改。要在单击单元格时提交更改,您必须处理 DataGridView.CurrentCellDirtyStateChanged 事件。在处理程序中,如果当前单元格是复选框单元格,则调用 DataGridView.CommitEdit 方法并传入 Commit 值。
这是我用来获取无线电行为的代码:
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
// Manually raise the CellValueChanged event
// by calling the CommitEdit method.
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
public void dataGridView1_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
// If a check box cell is clicked, this event handler sets the value
// of a few other checkboxes in the same row as the clicked cell.
if (e.RowIndex < 0) return; // row is sometimes negative?
int ix = e.ColumnIndex;
if (ix>=1 && ix<=3)
{
var row = dataGridView1.Rows[e.RowIndex];
DataGridViewCheckBoxCell checkCell =
(DataGridViewCheckBoxCell) row.Cells[ix];
bool isChecked = (Boolean)checkCell.Value;
if (isChecked)
{
// Only turn off other checkboxes if this one is ON.
// It's ok for all of them to be OFF simultaneously.
for (int i=1; i <= 3; i++)
{
if (i != ix)
{
((DataGridViewCheckBoxCell) row.Cells[i]).Value = false;
}
}
}
dataGridView1.Invalidate();
}
}