I have a Windows Forms app that displays a list of objects in a DataGridView.
This control renders bool values as checkboxes.
There’s a set of three checkboxes in the object properties that are mutually exclusive. At most one of them can be true. Accordingly I’d like the checkboxes to act like a set of radio buttons.
Just a side remark from the old guy: I think people these days don’t even know why these are called radio buttons. In the old days a radio in a car had 4 or 5 buttons, and depressing any one of them caused all the others to pop out. They were mutually exclusive. “Radio button” is probably not a helpful description these days because radios don’t have buttons like that anymore, I don’t think.
How can I do it? I figure if I attach a “CheckedChanged” event to the checkboxes, and I know the row, I will be able find all the other checkboxes.
What event can I hook to grab the checkbox control when it is first rendered, so that I Can attach the CheckedChanged event to it? I know about DataGridView.CellFormatting, but I think that’s wrong because it gets called every time the DataGridView paints. I really need an event that is called only the first time the DGV is rendered.
The one you want is CellContentClick, on the DGV itself. Attach a handler that checks to see if that column of the DGV is a CheckBoxCell, and if so, uncheck all other checkboxes on the row.
Just a note though, for a CheckBoxCell, this event fires before the checkbox value actually changes. This means that regardless of what you do to the current cell, it will be overridden by events that fire later. The behavior that will shake out of this is that you can have none of the cells on a row checked, by checking one box on the row and then checking it again (whether you try to set the checkbox value in the handler or not, the checkbox will end up cleared after the second click). To overcome that and force one of the checkboxes to be checked, you can handle CellValueChanged instead, and if the cell that changed is the current cell and is unchecked, check it.