如何取消选中DataGridView中的复选框 [英] How to cancel a checkbox in a DataGridView from being checked
问题描述
我有一个数据绑定的datagridview.如果不满足某些条件,如何取消在datagridview中选中的复选框?
I have a datagridview that is databound. How can I cancel the checkbox being checked in the datagridview if some condition is not met?
private void dataGridViewStu_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridViewStu.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dataGridViewStu_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
}
推荐答案
一种可能的方法是处理 DataGridView
上的 CurrentCellDirtyStateChanged
事件.检查您的条件,并确保当前单元格是 CheckBoxCell
,然后同时满足两个条件,则调用 CancelEdit
.
One possible way is to handle the CurrentCellDirtyStateChanged
event on DataGridView
. Check your condition and ensure the current cell is a CheckBoxCell
then call CancelEdit
if both conditions are met.
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (youShouldCancelCheck &&
this.dataGridView1.IsCurrentCellDirty &&
this.dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
{
this.dataGridView1.CancelEdit();
// Addition code here.
}
}
修改
我在 if
语句中添加了一个附加条件,以在运行 CancelEdit
和您的附加代码之前检查单元是否脏了.此操作不应再运行两次.发生了什么事:
I've added an additional condition to the if
statement to check if the cell is dirty before running the CancelEdit
and your additional code. This should no longer run twice. What was happening was:
- 用户点击复选框.
IsCurrentCellDirty = true
和CurrentCellDirtyStateChanged
被触发. - 满足条件.触发
CancelEdit
,这会取消所有更改并设置IsCurrentCellDirty = false
.因此,CurrentCellDirtyStateChanged
被再次触发.
- User clicks checkbox.
IsCurrentCellDirty = true
andCurrentCellDirtyStateChanged
is fired. - Conditions are met.
CancelEdit
is fired, which cancels all changes and setsIsCurrentCellDirty = false
. ThusCurrentCellDirtyStateChanged
is fired again.
CurrentCellDirtyStateChanged
仍将被触发两次,但条件中的代码仅在脏时才运行.
CurrentCellDirtyStateChanged
will still be fired twice, but code within the conditional will only be run when dirty.
这篇关于如何取消选中DataGridView中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!