我发现@Killercam 的解决方案可以工作,但如果用户双击太快,就会有点狡猾。不确定其他人是否也发现了这种情况。我在这里找到了另一个解决方案。
它使用数据网格的CellValueChanged
和CellMouseUp
. 长虹解释说
“原因是 OnCellvalueChanged 事件在 DataGridView 认为您已完成编辑之前不会触发。这对于 TextBox 列是有意义的,因为 OnCellvalueChanged 不会 [打扰] 为每个按键触发触发,但它不会 [有意义] 对于 CheckBox。"
以下是他的示例:
private void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
{
// Handle checkbox state change here
}
}
以及告诉复选框在单击时完成编辑的代码,而不是等到用户离开该字段:
private void myDataGrid_OnCellMouseUp(object sender,DataGridViewCellMouseEventArgs e)
{
// End of edition on each click on column of checkbox
if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
{
myDataGrid.EndEdit();
}
}
编辑:DoubleClick 事件与 MouseUp 事件分开处理。如果检测到 DoubleClick 事件,应用程序将完全忽略第一个 MouseUp 事件。除了 MouseUp 事件之外,还需要将这个逻辑添加到 CellDoubleClick 事件中:
private void myDataGrid_OnCellDoubleClick(object sender,DataGridViewCellEventArgs e)
{
// End of edition on each click on column of checkbox
if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
{
myDataGrid.EndEdit();
}
}