Search code examples
c#visual-studio-2010if-statementpicturebox

Visual C# cannot change picturebox.Image on click


I have a picturebox on an application on Visual Studio 2010 (on Visual C#).

The picturebox by default has an Image. I want the user to be able to click it and it would change to another Image and then if he clicks it again, the picturebox.Image would change back the first one etc..

 private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == WindowsFormsApplication2.Properties.Resources.English_flag)
            {
                pictureBox1.Image = WindowsFormsApplication2.Properties.Resources.Greek_flag;
            }
            else
            {
                pictureBox1.Image = WindowsFormsApplication2.Properties.Resources.English_flag;
            }
        }

This is what I have, but it doesn't work. I know there is something wrong with my if statement but I can't figure out what.

Edit: The first image appears on my Form, but when I click it, it doesn't change to the second one.


Solution

  • What you should try and rather have is a boolean flag that you toggle on every click.

    bool flag = true;
    private void pictureBox1_Click(object sender, EventArgs e)
        {
                pictureBox1.Image = flag ? WindowsFormsApplication2.Properties.Resources.Greek_flag 
                                         : WindowsFormsApplication2.Properties.Resources.English_flag;
            flag = !flag;
    
        }