【问题标题】:How to check null column values in SQL Database, C#如何检查 SQL 数据库中的空列值,C#
【发布时间】:2019-09-27 08:52:46
【问题描述】:

我在 Windows 窗体中使用 dataGridView 来显示数据库并希望为它着色。如果 [Solver] 列为 NULL,它应该绘制 LightSalmon,否则绘制 LightGreen。但是,即使列值为 NULL,它仍然会将其视为非 null 并绘制成 LightGreen。

This is my table:
      [Id]
      [Employee]
      [Section]
      [Machine]
      [Station]
      [MachNo]
      [Area]
      [Type]
      [Desc]
      [Recommendation]
      [Date]
      [Solver]
      [Process]


public void Color()
{
    for(int i = 0; i< dataGridView1.Rows.Count; i++)
        if (DBNull.Value.Equals(dataGridView1.Rows[11]))
        {
            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightSalmon;
        }
        else
        {
            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
        }   
}

【问题讨论】:

  • GRidView.Column 数据类型与 DBNull 不同
  • 也尝试实现dataGridView1.Refresh()

标签: c# sql winforms


【解决方案1】:

[Solver](第11列)是一列不是一行,所以需要检查每一行的列是否为空

public void Color()
{
    for(int i = 0; i< dataGridView1.Rows.Count; i++)
    {
        if (dataGridView1.Rows[i].Cells[11].Value == null || dataGridView1.Rows[i].Cells[11].Value == DBNull.Value)
        {
             dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightSalmon;
        }    
        else
        {
            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
        }
    }
}

【讨论】:

    【解决方案2】:

    宁可在该行上使用Cells 属性,例如

    if (DBNull.Value.Equals(dataGridView1.Rows.Cells[11].Value))
    

    【讨论】:

      【解决方案3】:

      你可以像下面这样使用

      dataGridView1.Rows[i].DefaultCellStyle.BackColor = dataGridView1.Rows[i].Cells[11].Value == null ? 
                                                                Color.LightSalmon : Color.LightGreen
      

      dataGridView1.Rows[i].DefaultCellStyle.BackColor = dataGridView1.Rows[i].Cells[11].Value == DBNull.Value ? 
                                                        Color.LightSalmon : Color.LightGreen
      

      【讨论】:

        【解决方案4】:
        for(int i = 0; i< dataGridView1.Rows.Count; i++)
            {  
                if (dataGridView1.Rows[i].Cells[11].Value == null || 
                dataGridView1.Rows[i].Cells[11].Value == DBNull.Value)
            {
                 dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
            }    
            else
            {
                dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2022-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-22
          • 2015-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多