0

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.

Swen22
  • 41
  • 3
  • Do favor [Int32.TryParse](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0) – LarsTech Jul 15 '21 at 14:35
  • @LarsTech TryParse from object ? interesting – Selvin Jul 15 '21 at 14:36
  • compare DBNull.Value with cell.Value ... if they are equals then yous should not execute your code – Selvin Jul 15 '21 at 14:37
  • also wrap with a `try catch` can do? – Lei Yang Jul 15 '21 at 14:37
  • @LeiYang catching expected exception ... interesting (but obviously wrong) approach – Selvin Jul 15 '21 at 14:39
  • @Selvin You're right. I forgot the Cell.Value is an object. I usually have a DataSource to avoid those issues. – LarsTech Jul 15 '21 at 14:40
  • the OP wants to solve crash. and doesn't specify what to do with null value. so i think try catch and just ignore is ok. – Lei Yang Jul 15 '21 at 14:43
  • @LeiYang if you had toothache you can simply extract a tooth but maybe you should try something less invasive first ... [catching exception is very costly](http://www.developerfusion.com/article/5250/exceptions-and-performance-in-net/) – Selvin Jul 15 '21 at 14:49

1 Answers1

0

It happens in the row where you use Convert.ToInt32(). You can add condition to check if cell.Value is null. I am not sure what you want to do with those kind of values but you can skip showing it by using 'continue' which will skip current iteration and goes to next:

private void MyDataGrid()
        {
            foreach (DataGridViewRow row in MyDataGrid.Rows)
            {
                var cell = row.Cells[5];

                if (cell.Value == null || cell.Value == DBNull.Value) 
                    continue;

                int val = Convert.ToInt32(cell.Value);
                if (val < 0)
                {
                    cell.Style.BackColor = Color.Red;
                }
                else if (val > 0)
                {
                    cell.Style.BackColor = Color.Green;
                }

            }
        }