Reputation: 23
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;
}
}
}
Upvotes: 0
Views: 3848
Reputation: 1523
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..
Upvotes: 1
Reputation: 125197
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;
}
Upvotes: 1