Home > Software engineering >  Data Grid View select box code erroring as null when box isn't checked
Data Grid View select box code erroring as null when box isn't checked

Time:11-29

I am making a for loop run the amount of times I have records in a table to see if a checkbox has been checked or not. It works however, the line of code which is used to actually see if there is something checked does not. It only works if it sees it in the top row but does not if it has to loop as it reports null.

            for(int i = 0; i < dgvForSale.Rows.Count; i  )
            {
                bool isCellChecked = (bool)dgvForSale.Rows[i].Cells[4].Value;

                if (isCellChecked == true)
                {
                    MessageBox.Show("Well this may have worked");
                }
                else
                {
                    MessageBox.Show("Empty");
                }
            }

The code that errors is " bool isCellChecked = (bool)dgvForSale.Rows[i].Cells[4].Value; "

I have tried changing it in some small ways but not really sure how to fix it without a whole different way of trying to see if the box is checked. I just expect it to be able to run.

CodePudding user response:

Refer to enter image description here

I did exactly reproduce your problem.

enter image description here

Your problem is due to the automatically added blank line.

The most correct way is to use dataGridView1.AllowUserToAddRows = false; to turn off adding rows by yourself.

There is another way, that is to add a line to judge null.

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    if (item.Cells[3].Value == null) { continue; }
    bool isCellChecked = (bool)item.Cells[3].Value;

    if (isCellChecked == true)
    {
        MessageBox.Show("Well this may have worked");
    }
    else
    {
        MessageBox.Show("Empty");
    }
}

CodePudding user response:

Try making your variable nullable. It seems the code will get crashed if cell value is null

bool? isCellChecked = (bool?)dgvForSale.Rows[i].Cells[4].Value;

and then check

if (isCellChecked !=null && isCellChecked == true)
{
   MessageBox.Show("Well this may have worked");
}
else
{
  MessageBox.Show("Empty");
}

  • Related