-1

There is an answer to a question like this here, but my question is why doing this the code is not working so please don't mark it as a "duplicate" of that question

So I have a dataGridView and in it a checkbox. So I want something to happen when I check and uncheck this box so I do:

private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
     Trace.WriteLine("Cell Content Click Col: " + e.ColumnIndex + " Row: " + e.RowIndex);

     if(e.ColumnIndex==0) //0 is the column of the checkbox
     {
       Trace.WriteLine("Value:"+  dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
     }
}

As you can see I am applying the answer of the other question. However the result is that no matter if I check or uncheck the box, the value is always false.

I am going to try this with CellValidating to see if I get better results, but what is the best way to check if a box is checked or unchekedon a dataGridView?

Tech Yogesh
  • 427
  • 4
  • 18
KansaiRobot
  • 7,564
  • 11
  • 71
  • 150

2 Answers2

0

Taken from this answer on the same link you posted in your question:

After an edit of values in the DataGridView, you should first commit the changes, so the internal values in the table are correctly updated:

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dataGridView1.IsCurrentCellDirty)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

Only then, you can correctly query the state of the checkbox:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    if (dgv.Rows.Count >= e.RowIndex + 1)
    {
        bool isChecked = (bool)dgv.Rows[e.RowIndex].Cells["CheckColumn"].Value;
        MessageBox.Show(string.Format("Row {0} is {1}", e.RowIndex, isChecked));
    }
}
RUL
  • 268
  • 2
  • 12
0
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    Trace.WriteLine("Cell Content Click Col: " + e.ColumnIndex + " Row: " + e.RowIndex);

    if (e.ColumnIndex == 0)
    {
        DataGridViewCheckBoxCell cell = dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
        if (cell != null)
        {
            Trace.WriteLine("Value:" + cell.EditingCellFormattedValue);
        }
    }
}
Z.R.T.
  • 1,543
  • 12
  • 15