RTX
RTX

Reputation: 109

add picturebox to the previous one

Hi there im working in vs with c#.I'm trying to make the algorithm that will add a random picturebox that already exists to the previous picturebox when the button is clicked.But i dont how to make it.I mean i have for exemple PictureBox1 on the screen,and when i click the button the second PictureBox should go to pictureBox1.Top - 90 because the picturebox is 90x90,when the button is clicked again the third goes on the top of second...

There is what i have for now,when i click the button,the new picture box just is added each time to the top-90 of the first PictureBox1:

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

    public static Random rand = new Random();  

    private void button1_Click_1(object sender, EventArgs e)
    {
        int box = rand.Next(1, 4);
        if (box == 1)
        { pictureBox2.Top = pictureBox1.Top - 90; }
        if (box == 2)
        { pictureBox3.Top = pictureBox1.Top - 90; }
        if (box == 3)
        { pictureBox4.Top = pictureBox1.Top - 90; }


    }

}

Upvotes: 0

Views: 97

Answers (1)

Abdullah Dibas
Abdullah Dibas

Reputation: 1507

Try this:

PictureBox _lastAddedPictureBox;
List<int> _notAddedBoxes = new List<int> {1,2,3};

private void button1_Click_1(object sender, EventArgs e)
{
    if(_lastAddedPictureBox == null)
    { 
      // if we assumed that pictureBox1 has been already added to the right location.
      _lastAddedPictureBox = pictureBox1;
    }

     int index = rand.Next(0, _notAddedBoxes.Count - 1);
     int box = _notAddedBoxes[index];

    if (box == 1)
    {
       pictureBox2.Top = _lastAddedPictureBox.Top - 90; 
       _lastAddedPictureBox  =  pictureBox2;
    }
    if (box == 2)
    { 
       pictureBox3.Top = _lastAddedPictureBox.Top - 90; 
      _lastAddedPictureBox  =  pictureBox3;
    }
    if (box == 3)
    { 
       pictureBox4.Top = _lastAddedPictureBox.Top - 90; 
       _lastAddedPictureBox  =  pictureBox4;
    } 

    // if we assume that you don't want to keep moving what has been already added.
    _notAddedBoxes.RemoveAt(index);
}

Upvotes: 1

Related Questions