0

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;
        }
    }
}
fixmycode
  • 8,220
  • 2
  • 28
  • 43
JamesHussey
  • 23
  • 1
  • 4
  • 1
    Are you sure the if true code is being hit, or that dgvPatList.Rows[i].Cells[0].Value.ToString() evaluates to "1"? – thewisegod Sep 06 '15 at 22:26

2 Answers2

1

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;
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
1

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..

enter image description here

Magic Mick
  • 1,475
  • 1
  • 21
  • 32