如何取消选中DataGridView中的复选框

问题描述:

我有一个数据绑定的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:

  1. 用户点击复选框. IsCurrentCellDirty = true CurrentCellDirtyStateChanged 被触发.
  2. 满足条件.触发 CancelEdit ,这会取消所有更改并设置 IsCurrentCellDirty = false .因此, CurrentCellDirtyStateChanged 被再次触发.
  1. User clicks checkbox. IsCurrentCellDirty = true and CurrentCellDirtyStateChanged is fired.
  2. Conditions are met. CancelEdit is fired, which cancels all changes and sets IsCurrentCellDirty = false. Thus CurrentCellDirtyStateChanged is fired again.

CurrentCellDirtyStateChanged 仍将被触发两次,但条件中的代码仅在脏时才运行.

CurrentCellDirtyStateChanged will still be fired twice, but code within the conditional will only be run when dirty.