简体   繁体   中英

C# Datagridview Image Column only displaying one image

I've added a Image Column to my datagrid in my c# winform, and I'm trying display an image depending on if the database value is "1". But all I get is the same image in all the rows that is set by the else statement, Here is the column info

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);

and here's the code to add the image

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;
        }
    }
}

Maybe your criteria is always true or always false.

But I Checked this way using a correct criteria and it works:

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;
}

This should work, assuming your condition of 1 is actually being hit.. It will also deal with null values (if any).

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;
}

Example shown below..

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM