我正在尝试将图标设置为每个我的db vaules为1,0的datagridview单元格 我使用此代码(从此网站复制!)
foreach (DataGridViewRow row in DataGridView1.Rows)
{ DataGridViewImageCell cell = row.Cells[8] as DataGridViewImageCell;
if row.Cells[8]==1)
cell.Value = (System.Drawing.Image)Properties.Resources.ok;
if row.Cells[8]==0)
cell.Value = (System.Drawing.Image)Properties.Resources.notOK;
}
但编译器显示此错误:
System.NullReferenceException was unhandled by user code
Message="Object reference not set to an instance of an object.
该代码有什么问题?
答案 0 :(得分:0)
试试这个。我想你想要这个
foreach (DataGridViewRow row in DataGridView1.Rows)
{
if (row.Cells[8]==1)
{
row.Cells[8]=new DataGridViewImageCell();
row.Cells[8].Value = (System.Drawing.Image)Properties.Resources.ok;
}
if (row.Cells[8]==0)
{
row.Cells[8]=new DataGridViewImageCell();
row.Cells[8].Value = (System.Drawing.Image)Properties.Resources.notOK;
}
}
修改强>
dataGridView1.Columns.Add("a", "Image");
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[8].ToString() == "1")
{
dataGridView1.Rows[i].Cells["a"] = new DataGridViewImageCell();
dataGridView1.Rows[i].Cells["a"].Value = (System.Drawing.Image)Properties.Resources.Config;
}
else
{
dataGridView1.Rows[i].Cells["a"].Value = (System.Drawing.Image)Properties.Resources.Config;
}
}
答案 1 :(得分:0)
DT.Columns.Add("c",System.Windows.Forms.DataGridViewImageCell);
for (int i = 0; i < DT.Rows.Count; i++) { if (DT.Rows[i][8].ToString() == "1")
DT.Rows[i]["a"] = (System.Drawing.Image)Properties.Resources.ok;
else
row.Cells[8].Value = (System.Drawing.Image)Properties.Resources.notOK;