I'm not 100% sure what causing this behavior, but I believe it has to do with the check box cell entering edit mode the moment you click inside of it. Confirmed, this issue is definitely caused by entering edit mode the moment you click inside the cell. See edit at the end of the post.
Because you are setting the value of the cell yourself, you can get around this issue by just making the check-box column readonly as well.
The following code worked fine for me in using LINQPad (I look liberties to simplify the handler logic):
void Main()
{
var dataGridView = new DataGridView();
dataGridView.Columns.Add(new DataGridViewCheckBoxColumn());
dataGridView.Columns.Add(new DataGridViewTextBoxColumn());
dataGridView.Columns.Add(new DataGridViewTextBoxColumn());
dataGridView.Columns[0].ReadOnly = true;
dataGridView.Columns[1].ReadOnly = true;
dataGridView.Columns[2].ReadOnly = true;
dataGridView.CellClick += this.DataGridView_CellClick;
dataGridView.Dump();
}
void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
var dataGridView = (DataGridView) sender;
var cell = dataGridView[0, e.RowIndex];
if (cell.Value == null) cell.Value = false;
cell.Value = !(bool)cell.Value;
}
The only oddity I noticed is the second click in a double-click doesn't get routed to the CellClick
event handler. If you really want this behavior you can tie the same handler to the CellDoubleClick
event.
Edit:
If you don't like making the first column read-only, then you can simply add a call to EndEdit
after you change the value:
void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
var dataGridView = (DataGridView) sender;
var cell = dataGridView[0, e.RowIndex];
if (cell.Value == null) cell.Value = false;
cell.Value = !(bool)cell.Value;
dataGridView.EndEdit();
}
This was hinted at by a comment on another question by user NeverHopeless.