2

I want to get a checkbox value from a datagridview(True/False) but I always get a value "null", here is the code where i get the value of the checkbox:

DataGridViewCheckBoxCell boolean = (DataGridViewCheckBoxCell)dgv[e.ColumnIndex, e.RowIndex];
string checkCheckboxChecked = ((bool)boolean.FormattedValue) ? "False" : "True";

This code returns a false in the Boolean.FormattedValue even the checkbox is checked and also I tried another:

object value = dgvVisual[e.ColumnIndex, e.RowIndex].Value;

And this code return a value of null

Why does this happen?

P.S. e is an event of the CELL CONTENT CLICK.

Here is the full code of the datagridview cell content click:

private void dgvVisual_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    int Number1= int.Parse(dgvVisual[0, e.RowIndex].Value.ToString());
    int Number2 = (e.ColumnIndex - 1);                
    DataGridViewCheckBoxCell boolean = (DataGridViewCheckBoxCell)dgvVisual[e.ColumnIndex, e.RowIndex];
    bool checkCheckboxChecked = (null != boolean && null != boolean.Value && true == (bool)boolean.Value);
    //string checkCheckboxChecked = "";
    if (checkCheckboxChecked)
    {
        //do something if the checkbox is checked
    }
    else
    {
        //do something if the checkbox isn't
    }
}

SOLVED: I changed the CELL END EDIT EVENT and add the click content to datagridview.CurrentCell to another cell.

Andro
  • 2,232
  • 1
  • 27
  • 40
User2012384
  • 4,769
  • 16
  • 70
  • 106

1 Answers1

1

Its a bit odd calling the cell boolean. And then using its FormattedValue property. I added a DataGridView to a Form, added two columns Text and Checkbox. CheckBox is a DataGridViewCheckBoxColumn. Then I added a button and this should give you the idea:

private void button1_Click(object sender, EventArgs e)
{
    dgv.AutoGenerateColumns = false;
    DataTable dt = new DataTable();
    dt.Columns.Add("Text");
    dt.Columns.Add("CheckBox");
    for (int i = 0; i < 3; i++)
    {
        DataRow dr = dt.NewRow();
        dr[0] = i.ToString();
        dt.Rows.Add(dr);
    }
    dgv.DataSource = dt;            
}

private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        var oCell = row.Cells[1] as DataGridViewCheckBoxCell;
        bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
    }
}
Rob
  • 4,927
  • 12
  • 49
  • 54
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321