[英]How to check null column values in SQL Database, C#
我在 Windows Forms 中使用 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;
}
}
而是使用該行上的Cells
屬性,例如
if (DBNull.Value.Equals(dataGridView1.Rows.Cells[11].Value))
[Solver]
(第11列)是列不是行,所以需要檢查每一行的列是否為null
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;
}
}
}
你可以像下面這樣使用
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
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.