3

I have created a DataGridViewImageColumn and want to perform operation if the value of the image cell is green check box image. The code is given below. But its not going inside the condition

if (dgvException.Rows[e.RowIndex].Cells["colStock"].Value 
                                              == Properties.Resources.msQuestion)
{
    //Some code
}

Please help.

cuongle
  • 74,024
  • 28
  • 151
  • 206
Pankaj Nagarsekar
  • 219
  • 1
  • 6
  • 17

3 Answers3

3

I would suggest using the cell Tag property to add a text value that represents the image - eg a number or name and use this to check what image is displayed. .

S.Ponsford
  • 43
  • 6
1

Checking equality for images using the equality operator (==) doesn't work the way you need it to work. That's why with your equality check always returns false.

You need to find out if the content of two images are the same -- to do this you'll need to do a pixel by pixel check of the image in the DGV cell and the reference image. I found a few links to this article that demonstrates comparing two images. I've taken the image comparison algorithm from the article and condensed it into a method that takes two Bitmaps to compare as parameters and returns true if the images are identical:

private static bool CompareImages(Bitmap image1, Bitmap image2) {
    if (image1.Width == image2.Width && image1.Height == image2.Height) {
        for (int i = 0; i < image1.Width; i++) {
            for (int j = 0; j < image1.Height; j++) {
                if (image1.GetPixel(i, j) != image2.GetPixel(i, j)) {
                    return false;
                }
            }
        }
        return true;
    } else {
        return false;
    }
}

(warning: code not tested)

Using this method your code becomes:

if (CompareImages((Bitmap)dgvException.Rows[e.RowIndex].Cells["colStock"].Value, Properties.Resources.msQuestion)) {
    //Some code 
} 
Jay Riggs
  • 53,046
  • 9
  • 139
  • 151
1

S.Ponsford answer worked very well in my case, I did this generic example. PD: Take on mind my column 0 is my DataGridViewImageColumn

if (this.dataGridView.CurrentRow.Cells[0].Tag == null)
{                                                    
     this.dataGridView.CurrentRow.Cells[0].Value= Resource.MyResource1;
     this.dataGridView.CurrentRow.Cells[0].Tag = true;                       
}
else
{
     this.dataGridView.CurrentRow.Cells[0].Value = Resources.MyResource2;
     this.dataGridView.CurrentRow.Cells[0].Tag = null;                        
}                         
Jones Joseph
  • 4,703
  • 3
  • 22
  • 40