How can I subscribe to an event handler of a CheckBox in a CheckBoxColumn of a DataGridView similar to the CheckChanged or Click event handler of a regular CheckBox? I have one or more columns, in multiple data grids in my application that I want to do this for.
I’ve looked at CellContentClick and CellClick, but they seem totally inelegant, because they fire for every click in the data grid, not just for the Cell or CheckBox of interest.
The solution below came from pouring over the MSDN documentation and a little luck in some tangential threads here and on CodeProject.
The idea is to create a class, derived from DataGridViewCheckBoxCell, that includes a handler that is triggered along with the ContentClick. This may seem like lots of overhead for one DataGridView, but my application has many DataGridViews, so this code is reusable, thus saving time.
Since I wanted to be able to reference this cell class from a column class, I also implemented a class derived from DataGridViewCheckBoxColumn:
Trimming away extraneous code, I’m using it like this:
The column class could be eliminated, and it could be used as follows:
Here’s a sample event handler. The state of another column in the data grid is updated, based on the value of this column and conditionally some state information in the WasReleased property. The DataGridView’s DataSource is a collection of Specimen objects, so each row’s DataBoundItem is a Specimen. The Specimen class is application specific, but it has properties OnHold, displayed by this column; IsReleased, displayed by another column; and WasReleased.
Good style would probably push some of the code in the event handler down into a method in the Specimen class.