问题
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:
- User clicks checkbox.
IsCurrentCellDirty = trueandCurrentCellDirtyStateChangedis fired. - Conditions are met.
CancelEditis fired, which cancels all changes and setsIsCurrentCellDirty = false. ThusCurrentCellDirtyStateChangedis 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