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)
{
}
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:
IsCurrentCellDirty = true
and CurrentCellDirtyStateChanged
is fired.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.