So I'm trying to create a simple program that just change the picture in a picture box when it's clicked. I'm using just two pictures at the moment so my code for the picture box click event function looks like that:
private void pictureBox1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == Labirint.Properties.Resources.first)
pictureBox1.Image = Labirint.Properties.Resources.reitmi;
else if (pictureBox1.Image == Labirint.Properties.Resources.reitmi)
pictureBox1.Image = Labirint.Properties.Resources.first;
}
For some reason the if statement it's not working and the picture don't change. What should I do?
Note: original code contained bug with second if
undoing effect of first if condition would work with fix suggested by Cyral's answer, but adding else
did not fix the issue - stepping through the code with else
still shows no matches for either image.
if (pictureBox1.Image == Labirint.Properties.Resources.first)
pictureBox1.Image = Labirint.Properties.Resources.reitmi;
if (pictureBox1.Image == Labirint.Properties.Resources.reitmi) // was missing else
pictureBox1.Image = Labirint.Properties.Resources.first;
Maybe this code can be a bit large, but works just fine with me, try it:
This is the requeriment:
And here is the code to compare:
this code compares each byte image to generate the result. may have other easier ways.
There's a trap here that not enough .NET programmers are aware of. Responsible for a lot of programs that run with bloated memory footprints. Using the Labirint.Properties.Resources.xxxx property creates a new image object, it will never match any other image. You need to use the property only once, store the images in a field of your class. Roughly:
And now you can compare them:
And to avoid the memory bloat:
You need to use
else if
, because if the image isfirst
, you set it toreitmi
, then you check if it isreitmi
, which it now is, and change it back tofirst
. This ends up not appearing to change at all.