jeudi 15 novembre 2018

Error when clicking a checkbox in a dataGrid

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.




Aucun commentaire:

Enregistrer un commentaire