问题
I need to change the colors of a data grid view rows according to the data in the rows.
My code is:
foreach (DataGridViewRow Myrow in datagrid1.Rows)
{
if (Myrow.Cells[0].Value.Equals("Red"))
{
Myrow.DefaultCellStyle.BackColor = Color.Red;
}
{
Myrow.DefaultCellStyle.BackColor = Color.Green;
}
}
But when I try to run it I get: Object reference not set to an instance of an object
I assume it's because it keeps looping every row until it reaches some which has a null value. How do I stop it from doing that?
回答1:
I figured out I needed to change the DataGridView AllowUserToAddRows to false and that got rid of the empty row at the bottom which gave me the null value.
I'll leave this here if anybody else gets into the same situation.
来源:https://stackoverflow.com/questions/39657748/object-reference-not-set-to-an-instance-of-an-object-when-changing-datagridview