2017-03-04 107 views
0

嗨有即時通訊工作vs與C#。我試圖使算法,將添加一個隨機的圖片框已存在的前一個圖片框,當按鈕被點擊。但我不知道如何使它。我的意思是我有例如PictureBox1在屏幕上,當我點擊按鈕時,第二個PictureBox應該去pictureBox1.Top - 90,因爲圖片框是90x90,當再次點擊按鈕時,第三個在頂部第二...將圖片框添加到前一個

有我有什麼,現在,當我按一下按鈕,新的圖片框只是每次加到第一PictureBox1的頂級90:

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; } 


    } 

} 
+0

很難猜測是什麼意圖。描述你想要完成的事情,而不是談論那些肯定不會做你想完成的代碼。 –

+0

我解釋說,我已經爲例4個圖片框,在按鈕上單擊下一個圖片框等於以前的picturebox.top - 90px,這就是所有。 – RTX

回答

1

試試這個:

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); 
} 
+0

作品完美,謝謝 – RTX

+0

嘿,再次,我還有一個問題,如果你可以help.Now,如果我點擊按鈕,4次後,pictureboxes將不會再添加。但我如何做到這一點?每次添加pictureboxes該按鈕被點擊(無限)?謝謝 – RTX