DataGridView CheckBox events

Ultimately, it was the CurrentCellDirtyStateChanged event that does it, but you need to do it in the right way. And the right way is MSDN's, though it doesn't make sense at first glance.

A fragment from above, and what I ultimately did is below:

    // Hook up the event handler so that we can change the "corresponding" checkboxes as needed
    dgvSysGrid.CurrentCellDirtyStateChanged += new EventHandler(dgvSysGrid_CurrentCellDirtyStateChanged);
    dgvSysGrid.CellValueChanged += new DataGridViewCellEventHandler(dgvSysGrid_CellValueChanged);

}

void dgvSysGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    Point cur = new Point(e.ColumnIndex, e.RowIndex);

    // Change the diagonal checkbox to the opposite state
    DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)dgvSysGrid[cur.X, cur.Y];
    DataGridViewCheckBoxCell diagCell = (DataGridViewCheckBoxCell)dgvSysGrid[cur.Y, cur.X];
    if ((bool)(curCell.Value) == true)
    {
        diagCell.Value = false;
    }
    else
    {
        diagCell.Value = true;
    }
}

void dgvSysGrid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgvSysGrid.IsCurrentCellDirty)
    {
        dgvSysGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

Basically, all that's happening is the CurrentCellDirtyStateChanged event triggers the CellValueChanged event, and that's it. If you just attach the CellValueChanged event, then it only triggers AFTER you have left the cell. I don't know why exactly (considering it's a checkbox, isn't it "done" immediately?), but that's what happens. And the code as above works, in that the check box changes go in RIGHT away when clicking it. So it works.


You can use the CellValidating event and the e.FormattedValue will have the changed value. If you perform some check, and dont want the value to update, set e.Cancel to true.

Here is the example from the FormattedValue page:

private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    dataGridView1.Rows[e.RowIndex].ErrorText = "";
    int newInteger;

    // Don't try to validate the 'new row' until finished 
    // editing since there
    // is not any point in validating its initial value.
    if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
    if (!int.TryParse(e.FormattedValue.ToString(),
        out newInteger) || newInteger < 0)
    {
        e.Cancel = true;
        dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a non-negative integer";
    }
}