C# .NET Datagrid – Events Don’t Trigger For Check Boxes Within A DataGrid

Background

I had a datagrid which contains a check box in column one. I wanted to trigger an event when any of the check boxes in column one were selected within the datagrid. This should be quite easy to achieve using the CellValueChanged event, however this would only fire on clicking the check box before the check (tick) had appeared. This would mean that when enumerating each line the check box would still not have a checked item and therefore this would not be what I had expected.

Solution

I found that in addition to the CellValueChanged event I needed to also have an event Cell_ContactClick as below

private void dataGridViewMain_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    this.dataGridViewMain.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

I assume CommitEdit states that I have finished editing, now commit the changes straight away and therefore the CellValueChanged is fired again after the check mark has had a chance to appeared in the check box., after which my enumerating each line for a check box would work.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.