7
votes

I'm having a strange issue here.

I have a 3 column datagrid that is filled by a connection with the database. So far so good.

I have an extra column, of checkbox type. I need to get it's value for perfoming a bulk operation on it. Here is the catch:

When all cells are selected, it works fine. But when an user selects any cell that its not the first, software gives me a object reference exception.

Here is the code

public List<String> GetSelected()
{
    List<String> selected = new List<String>();
    foreach(DataGridViewRow row in datagrid.rows)
    {
        if ((Boolean)row.Cells[wantedCell].Value == true)
        {
            selected.Add(row.Cells[anotherCell]);
        }
    }
}

I tracked down the failure to the if-test, throwing a exception, because the value of the cell is read as null.

Any thougths?

Thanks

4
Which line throws the exception?SLaks
Just an example of index. not the real cell name or index. The funny thing is that i already solved this one. Instead of converting the value like: (Boolean)row.Cells[i].Value i used Convert.ToBoolean(row.Cells[i]) and works fine. Thanks for your help! :DGeorge Silva
Your problem was probably that row.Cells[wantedCell].Value was null, which you were trying to cast to bool. (A non-nullable type)SLaks
@SLaks Close. The value was DbNull.ValueWonderWorker

4 Answers

4
votes

try this:

public List<String> GetSelected()
{
    List<String> selected = new List<String>();
    foreach(DataGridViewRow row in datagrid.Rows)
    {
        object value = row.Cells[wantedCell].Value;
        if (value != null && (Boolean)value)
        {
            selected.Add(row.Cells[anotherCell]);
        }
    }
}
1
votes

This didn't work for me (an exception was thrown converting to a Boolean).

I believe that this does the job:

foreach (DataGridViewRow row in dgv.SelectedRows)
{
    bool b = row.Cells[0].Value == DBNull.Value ? false : (bool)row.Cells[0].Value;
    ...
 }
0
votes

Replace row 6 with if (row.Cells[wantedCell].Value == DBNull.Value ? false : (bool)row.Cells[wantedCell].Value == true) to make this:

public List<String> GetSelected()
{
    List<String> selected = new List<String>();
    foreach(DataGridViewRow row in datagrid.rows)
    {
        if (row.Cells[wantedCell].Value == DBNull.Value ? false : (bool)row.Cells[wantedCell].Value == true)
        {
            selected.Add(row.Cells[anotherCell]);
        }
    }
}
0
votes

Default value on "unchecked" checkboxcell in datagridview is DBNull. You can change this at its column by setting CheckBoxColumn FalseValue attribute:

DataGridViewCheckBoxColumn CheckCol = new DataGridViewCheckBoxColumn();
CheckCol.FalseValue = false;

This will resolve your issue with the cell being read as null.