I'm using Datagridview to get data from my sql server. I'm trying to change color of the cell according to their value. However, if there is a null data on the column, it crashes. I'm using .NET Framework 4.0. Here is the code:
private void MyDataGrid()
{
foreach (DataGridViewRow row in MyDataGrid.Rows)
{
var cell = row.Cells[5];
int val = Convert.ToInt32(cell.Value);
if (val < 0)
{
cell.Style.BackColor = Color.Red;
}
else if (val > 0)
{
cell.Style.BackColor = Color.Green;
}
}
}
This is the error:
An unhandled exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: Object cannot be assigned to other types from DBNull.