0

我正在尝试将图标设置为每个我的数据库值 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.

该代码有什么问题?

4

2 回答 2

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;

                }
            }
于 2013-10-29T10:09:49.273 回答
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;

于 2013-11-02T08:38:49.240 回答