单元格格式中的空值

null value in cellformatting

我有一个名为 dgMember_Grade 的数据网格,它从存储过程中获取数据。

它的一列表示一个名为 vacationStart 的日期。

我想根据单元格值为行着色,但它在 foreach 行给我一个错误:

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

我试过代码:

 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;
                    }
                }
            }

        }

如果您已经知道单元格的索引。 可能您正在尝试这样做:

foreach (DataGridViewRow Myrow in dgMember_Grade.Rows)
{
    if (Myrow.Cells[26].Value == null) {
        continue;
    }

    DateTime expiredate = DateTime.Parse(Myrow.Cells[26].Value.ToString());
    if (expiredate < DateTime.Now) 
    {
        Myrow.DefaultCellStyle.BackColor = Color.Red;
    }
    else
    {
        Myrow.DefaultCellStyle.BackColor = Color.Green;
    }
}

这是您可以使用的代码:

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;
    }
}

注:

  • 您不需要 2 个循环,您可以简单地在 Rows 之间使用一个循环并根据 Myrow.Cells[26].Value
  • 应用您需要的内容
  • 您可以使用 CellFormattingCellPaintingRowPrePaint 等事件来应用格式。