Search code examples
c#winformsdatagridviewdatagridviewcolumndatagridviewcheckboxcell

DataGridViewCheckBox row returns null until checkbox is clicked


I've created a windows form with a DataGridView and added a column that will contain a checkbox for each row. A DataTable is bound to the DataGridView and then a DataGridViewCheckBoxColumn is added.

When my form is closed I attempt to get the value of the checkbox in each row but if the checkbox in a row has not been checked by the user at any point then the program just returns its value as null when I feel it should return false (not checked). Why is this and what can I do to solve it?

//add checkbox column
DataGridViewCheckBoxColumn mCheckboxColumn = new DataGridViewCheckBoxColumn();
mCheckboxColumn.Name = "chk";
mCheckboxColumn.HeaderText = "checkbox";       
dgv.Columns.Add(mCheckboxColumn);



//looping through each row
foreach (DataGridViewRow row in dgv.Rows)
{
     if ((bool)row.Cells["chk"].Value == true)
     {
          MessageBox.Show("checked!");
     }
}

Solution

  • I believe the reason why you are experiencing nulls is because you are adding a new column to a data grid after its bound to your data source. It therefore has no default value whilst unchecked.

    You can get around it with the following small change. ConvertTo.Boolean will return false when it encounters a null, whereas a cast to (bool) which i think is Boolean.Parse doesn't.

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells["chk"];
    
        if (Convert.ToBoolean(cell.Value))
        {
            MessageBox.Show("checked!");
        }
    }
    

    Hope that helps