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 Fu

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.