[英]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
和您的附加代碼之前檢查單元格是否臟了。 此操作不應再運行兩次。 發生了什么事:
IsCurrentCellDirty = true
並觸發CurrentCellDirtyStateChanged
。 CancelEdit
,取消所有更改並設置IsCurrentCellDirty = false
。 因此, CurrentCellDirtyStateChanged
被再次觸發。 CurrentCellDirtyStateChanged
仍將被觸發兩次,但條件中的代碼僅在臟時才運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.