簡體   English   中英

如何取消選中DataGridView中的復選框

[英]How to cancel a checkbox in a DataGridView from being checked

我有一個數據綁定的datagridview。 如果不滿足某些條件,如何取消在datagridview中選中的復選框?

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

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

一種可能的方法是處理DataGridView上的CurrentCellDirtyStateChanged事件。 檢查您的條件,並確保當前單元格是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 = true並觸發CurrentCellDirtyStateChanged
  2. 滿足條件。 CancelEdit ,取消所有更改並設置IsCurrentCellDirty = false 因此, CurrentCellDirtyStateChanged被再次觸發。

CurrentCellDirtyStateChanged仍將被觸發兩次,但條件中的代碼僅在臟時才運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM