I am using a dataGrid that has a checkbox in one of its columns. I want to detect when this checkbox is clicked and unclicked and do something, so I did this:
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
Trace.WriteLine("Cell Content Click Col: " + e.ColumnIndex + " Row: " + e.RowIndex);
if(e.ColumnIndex==0) //it is a check
{
Trace.WriteLine("Value:"+ dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
}
dataGridView2.CommitEdit(DataGridViewDataErrorContexts.Commit); //This has to be put here in order for CellValueChanged to work
//see https://stackoverflow.com/a/11844206/4451521
}
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
Trace.WriteLine("Cell value changed " + e.ColumnIndex + " Row: " + e.RowIndex);
Trace.WriteLine("Value:" + dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
if(e.ColumnIndex==0&& (bool)dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value==true)
{
dataGridView2.Rows[e.RowIndex].Cells["Quantity"].Value = 1.0;
}
else if (e.ColumnIndex == 0 && (bool)dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == false)
{
dataGridView2.Rows[e.RowIndex].Cells["Quantity"].Value = 0;
}
Trace.WriteLine("----------------------------");
Merge();//an algorithm to merge rows when necessary
}
Now, this works great like 99% of the time. Everytime I click the checkbox (column 0) I get
Cell Content Click Col: 0 Row: 4
Value:False
Cell value changed 0 Row: 4
Value:True
Cell value changed 4 Row: 4
Value:1
So changing it from False to True and setting column 4 to 1.
And every time I uncheck it I get
Cell Content Click Col: 0 Row: 4
Value:True
Cell value changed 0 Row: 4
Value:False
Cell value changed 4 Row: 4
Value:0
This time changing it from True to False and setting column 4 to 0
However if I start playing with the check and uncheck multiple times, sometimes even when I check it (or uncheck it-it happens in both situations) the function CellContentClick
does not register.
Meaning that eventhough I have "clicked the content" (by checking or unchecking it) the function is not called. Resulting in the bad behavior that the column is checked but the value in column 4 is not 1 (or viceversa)
This occurs sporadically, but I am wondering why this is happening and how to correct it.
EDIT:
Tried the answer suggested in the "duplicate" question and it actually does not work. Furthermore, it makes the situation worse. In the original problem, sometimes (1% of the cases) the click does not work but once you click it again everything runs as normal. In the other question, the answer (trying CellClick) does not change the other column. and worse of all once it does not work it keeps not working for all the rest. For example I check it and the value did not change. Then I uncheck it and now the value changes to 1 (not 0!). and when I check it again t changes to 0 (not 1!). The solution does not work