C#Datagridview图像列仅显示一个图像

时间:2015-09-06 22:00:02

标签: c# winforms datagridview

我在我的c#winform中为我的数据网格添加了一个图像列,我正在尝试显示图像,具体取决于数据库值是否为“1”。但是我得到的是在else语句设置的所有行中的相同图像, 这是列信息

dgvPatList.Columns[8].Name = "NPO";
dgvPatList.Columns[8].HeaderText = "NPO";
dgvPatList.Columns[8].DataPropertyName = "NPO"
dgvPatList.Columns[8].Width = 50;
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.HeaderText = "NPO";
imageColumn.Name = "NPOIMG";
dgvPatList.Columns.Add(imageColumn);

这是添加图片的代码

private void dgvPatList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    int number_of_rows = dgvPatList.RowCount; 
    for (int i = 0; i < number_of_rows; i++)
    {
        if (dgvPatList.Rows[i].Cells[0].Value.ToString() == "1")
        {
            Icon image =  Properties.Resources.Tick_Green; 
            this.dgvPatList.Rows[i].Cells["NPOIMG"].Value = image;
        }
        else
        {
            Icon image = Properties.Resources.no_results; 
            this.dgvPatList.Rows[i].Cells["NPOIMG"].Value = image;
            //((DataGridViewImageCell)this.dgvPatList.Rows[i].Cells["NPOIMG"]).Value = Properties.Resources.no_results;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

也许您的标准始终为真或始终为假。

但是我使用正确的标准检查这种方式并且有效:

foreach (DataGridViewRow row in myDataGridView.Rows)
{
    if (row.IsNewRow)
        continue;
    if (row.Cells[0].Value.ToString() == "1")
        row.Cells["ImageColumn"].Value = Properties.Resources.Image1;
    else
        row.Cells["ImageColumn"].Value = Properties.Resources.Image2;
}

答案 1 :(得分:1)

这应该有效,假设您的条件1实际上被击中..它还将处理空值(如果有的话)。

foreach (DataGridViewRow dgRow in dgvPatList.Rows)
{
    if (dgRow.Cells[0].Value == null) continue;  //Change if you wish no_results to be shown

    dgRow.Cells["NPOIMG"].Value = dgRow.Cells[0].Value.ToString() == "1" 
         ? Properties.Resources.Tick_Green 
         : Properties.Resources.no_results;
}

以下示例..

enter image description here