Search code examples
c#sql-serverwinformscell-formatting

null value in cellformatting


I have a datagrid called dgMember_Grade that takes its data from a stored procedure.

One of its columns represent a date called vacationStart.

I want to color the rows based on cell value, but it gives me an error on the foreach line:

Cannot convert type 'char' to 'System.Windows.Forms.DataGridViewCell'

I tried the code:

 foreach (DataGridViewRow Myrow in dgMember_Grade.Rows)
        {
            foreach (DataGridViewCell cell in Myrow.Cells[26].Value.ToString()) // error on foreach 
            {
                if (cell != null)
                {
                    DateTime date = DateTime.Now;
                    DateTime expiredate = DateTime.Parse(Myrow.Cells[26].Value.ToString());

                    if (expiredate < date) 
                    {
                        Myrow.DefaultCellStyle.BackColor = Color.Red;
                    }
                    else
                    {
                        Myrow.DefaultCellStyle.BackColor = Color.Green;
                    }
                }
            }

        }

Solution

  • Here is the code you can use:

    foreach (DataGridViewRow Myrow in dgMember_Grade.Rows)
    {
        var cellValue = Myrow.Cells[26].Value;
        if (cellValue == null || cellValue == DBNull.Value)
            continue;
    
        DateTime expiredate = Convert.ToDateTime(cellValue);
        if (expiredate < DateTime.Now)
        {
            Myrow.DefaultCellStyle.BackColor = Color.Red;
        }
        else
        {
            Myrow.DefaultCellStyle.BackColor = Color.Green;
        }
    }
    

    Note:

    • You don't need 2 loops, You can simply use a loop betwen Rows and apply what you need based on Myrow.Cells[26].Value
    • You can use events like CellFormatting or CellPainting or RowPrePaint to apply formatting.