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
I did exactly reproduce your problem.
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");
}