How to cancel a checkbox in a DataGridView from being checked

混江龙づ霸主 提交于 2021-01-28 08:03:32

问题


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)
{
}

回答1:


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.
  }
}

Edit

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. 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 will still be fired twice, but code within the conditional will only be run when dirty.



来源:https://stackoverflow.com/questions/28347199/how-to-cancel-a-checkbox-in-a-datagridview-from-being-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!