1

I tried to get value of checked checkbox in DataGridView, so I check if value is true or false:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex != -1)
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = false;
                    }
                    else
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = true;
                    }

                    button2.Enabled = (counter > 0);

                }
            }
        }
    } 

It involks an error in line:

if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)

Second solution:

 if (dataGridView1.Rows[i].Cells["check"].Value == null || (bool)dataGridView1.Rows[i].Cells["check"].Value == false)
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = true;

                        counter++;
                    }
                    else
                    {

                        dataGridView1.Rows[i].Cells["check"].Value = false;

                        counter--;
                    }

The code below works, but sometimes checkbox is not checked

ITMANAGER
  • 131
  • 1
  • 3
  • 10

1 Answers1

2

I am doing something really similar in a project of mine, I am only using OnCellValueChanged instead of CellContentClick.

Here's my working line of code

bool completed = Convert.ToBoolean(dgv.Rows[e.RowIndex].Cells[1].Value.ToString());

What is exactly your error? Did you try to see what .Value was in the debugger ?

TinkeringMatt
  • 181
  • 1
  • 9