Josh
Josh

Reputation: 180

Show a different image everytime the button is clicked

I am trying to make a button that will display a different image ever time it gets clicked in C# by integer increment

C#

private void button1_Click(object sender, EventArgs e)
 {
  int a = 0;

    a++;

    if (a == 1)
    {
        pictureBox1.ImageLocation = "http://s20.postimg.org/uazs6u2p9/99639488.png";
    }
    else if (a == 2)
    {
        pictureBox2.ImageLocation = "http://s20.postimg.org/cdopdvz8t/99639514.png";
    }
}

Upvotes: 0

Views: 83

Answers (1)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19179

You have declared int a inside method so every time you click button a new int with value of 0 is created. and you always increment 0 to 1.

Instead declare int a as a field. also put a default condition to reset the counter when it reaches the maximum available cases.

private int a = 0;
private void button1_Click(object sender, EventArgs e)
{
    a++;

    switch(a)
    { 
        case 1: pictureBox1.ImageLocation = "http://s20.postimg.org/uazs6u2p9/99639488.png";
                break;
        case 2: pictureBox2.ImageLocation = "http://s20.postimg.org/cdopdvz8t/99639514.png";
                break;

        // put more cases here

        default: a = 0; // reset counter
                 break;
    }
}

There is also another way, instead of using int and display images in sequence you can use random int and randomize images.

private Random r = new Random();
private void button1_Click(object sender, EventArgs e)
{
    switch(r.Next(1,2))
    { 
        case 1: pictureBox1.ImageLocation = "http://s20.postimg.org/uazs6u2p9/99639488.png";
                break;
        case 2: pictureBox2.ImageLocation = "http://s20.postimg.org/cdopdvz8t/99639514.png";
                break;

        // put more cases here
    }
}

r.Next(x,y) simply produces a random number between x and y. so if you have 10 cases you must do r.Next(1,10). if you have 6 cases do r.Next(1,6) etc...

Upvotes: 1

Related Questions