【问题标题】:null value in cellformatting单元格格式中的空值
【发布时间】:2015-10-13 05:40:29
【问题描述】:

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

其中一列代表名为vacationStart的日期。

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

无法将类型“char”转换为“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;
                    }
                }
            }

        }

【问题讨论】:

    标签: c# sql-server winforms cell-formatting


    【解决方案1】:

    这是你可以使用的代码:

    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 等事件来应用格式设置。

    【讨论】:

    • 如果另一个名为 (dgavacation) 的数据网格中的列 (vacationStart) ....?
    • Myrow.Cells[26]你可以使用列索引,或者Myrow.Cells["columnName"]
    • 我不能使用var cellValue = dgVacation.Cells["vacationStart"].Value;
    • 有什么问题?我不知道 26 但Myrow.Cells[INDEX].Value(放置列的索引而不是索引)将起作用,并且值的类型为object
    • 我会尝试更清楚...我想根据另一个名为 dgavacation 的数据网格中的单元格值(日期)为数据网格 dgMember_Grade 着色
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多