Search
Close this search box.

How to get a CheckBox in a Winforms DataGridView to react to the first click

I had this problem today. It looks very simple, but actually took me a while to find a solution. The problem is: I have a Winforms DataGridView, and its first column is an unbound CheckBox column which is used to select/unselect a row. I want to hook up the check/uncheck event so that I can execute some logic after a row is selected or unselected. As this is Winforms, there is no way I can hook up an event from a control’s child element. But, it is quite obvious that we can hook up DataGridView’s OnCellvalueChanged event and put the logic there. So I had some code like this:

private void EmployeesGrid_OnCellValueChanged(object sender,  

     DataGridViewCellEventArgs e)

{

     if (e.ColumnIndex == 0 && e.RowIndex > -1)

     {

        bool selected = (bool)_gvEmployees[e.ColumnIndex, e.RowIndex].Value;

        _gvEmployees.Rows[e.RowIndex].DefaultCellStyle.BackColor =

selected ? Color.Yellow : Color.White;

     }

}

Here, for demonstration, I just simple change the background color of a row depending on if the checkbox column is checked or not. It all works fine except the background color won’t change until you move your mouse cursor out of the cell. The reason for that is OnCellvalueChanged event won’t fire until the DataGridView thinks you have completed editing. This makes senses for a TextBox Column, as OnCellvalueChanged wouldn’t broth to fire for each key strike, but it doesn’t for a CheckBox.

After trying a few different events, I finally find a workaround, and it is very simple. I just need to hook up on CellMouseUp event and explicitly exit edit mode there. Some sample code is here:
private void EmployeesGrid_OnCellMouseUp(object sender,  

     DataGridViewCellMouseEventArgs e)

{

     if (e.ColumnIndex == 0 && e.RowIndex > -1)

     {

        _gvEmployees.EndEdit();

     }

}
This article is part of the GWB Archives. Original Author: Changhong’s Technical Blog

Related Posts