Reputation: 1860
I am currently working on a project that utilizes a DataGridView block to display search results of data that is pulled from a remote MySQL database.
I am trying to re-color the background of each row based on the string value of one of the columns
The code:
foreach (DataGridViewRow row in this.dgvSearchResults.Rows)
{
if (row.Cells[4].Value.ToString() == "Outbound")
{
row.DefaultCellStyle.BackColor = Color.LightSkyBlue;
}
else if (row.Cells[4].Value.ToString() == "Inbound")
{
row.DefaultCellStyle.BackColor = Color.LightCyan;
}
else
{
row.DefaultCellStyle.BackColor = Color.White;
};
}
My Error:
Object reference not set to an instance of an object
I can't seem to figure this one out, any feedback is helpful!
Upvotes: 0
Views: 134
Reputation: 1706
Make sure that there are actually at least 5 cells (C# arrays are 0 bound) and make sure Value
where you call .ToString()
on is not null
.
For the latter one you can do the following:
if (row.Cells[4].Value != null)
{
if (row.Cells[4].Value.ToString() == "Outbound")
{
row.DefaultCellStyle.BackColor = Color.LightSkyBlue;
}
else if (row.Cells[4].Value.ToString() == "Inbound")
{
row.DefaultCellStyle.BackColor = Color.LightCyan;
}
else
{
row.DefaultCellStyle.BackColor = Color.White;
}
}
else
{
row.DefaultCellStyle.BackColor = Color.White;
}
Upvotes: 2