简体   繁体   中英

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.

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;

    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

            private Image first;
            private Image reitmi;
            private Image reitmi2;
            private Image selectForCancel;

 private void Form2_Load(object sender, EventArgs e)
            {

                first = Properties.Resources.Open;
                reitmi = Properties.Resources.Select;
                reitmi2 = Properties.Resources.Reserve;



                pictureBox1.Image = Properties.Resources.Open;

    }

private void pictureBox2_Click(object sender, EventArgs e)
        {    
        if (pictureBox2.Image == first)
                {
                    pictureBox2.Image = reitmi;

                    listHoldingSeats.Items.Add("B1");
                    txtListCount.Text =listHoldingSeats.Items.Count.ToString();

                }


                else
                {
                    pictureBox2.Image = first;
                    listCancelledList.Items.Add("B1");
                } 


        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM