2015-02-05 61 views
1

我有一个datagridview是数据绑定。如果不满足某些条件,我如何取消在datagridview中选中的复选框?如何取消选中DataGridView中的复选框

private void dataGridViewStu_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    dataGridViewStu.CommitEdit(DataGridViewDataErrorContexts.Commit); 
} 

private void dataGridViewStu_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
{ 
} 

回答

2

一种可能的方式是处理上DataGridViewCurrentCellDirtyStateChanged事件。检查你的状况,并确保当前单元格是CheckBoxCell,如果两个条件都满足,则调用CancelEdit

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和你额外的代码之前脏。这应该不再运行两次。发生了什么是:

  1. 用户单击复选框。 IsCurrentCellDirty = trueCurrentCellDirtyStateChanged被解雇。
  2. 符合条件。 CancelEdit被解雇,取消所有更改并设置IsCurrentCellDirty = false。因此CurrentCellDirtyStateChanged再次被激发。

CurrentCellDirtyStateChanged仍然会被触发两次,但条件内的代码只会在脏时运行。

+1

我试过你的代码,它“工作”,但我需要在CancelEdit方法后运行额外的代码,它似乎运行两次额外的代码。它应该只运行一次。 – Jnr 2015-02-06 06:51:39

+0

@Jnr你在哪里运行额外的代码,所以我可以重现错误?我明天会看看。 – OhBeWise 2015-02-06 07:02:52

+0

让我在你的答案中编辑你的代码,以便你明白我的意思。 – Jnr 2015-02-06 07:26:30