2017-04-05 102 views
0

我試圖把在隨機位置的一些按鈕的Windows窗體像這樣:如何在for循環中添加buttonlocation?

for (int i = 0; < shuffle.Length; i++) 
{ 
    //This line doesn't work 
    Controls["button" + (i + 1).ToString()].Location = new Point(shuffle[i], 250); 

    //But this line is OK 
    Controls["button" + (i + 1).ToString()].Text = text[i]; 
} 

當我寫的下一行是工作正常,但如何把它放在一個循環,改變1,2和3 (i +1)?

button1.Location = new Point(shuffle[0], 250); 
button2.Location = new Point(shuffle[1], 250); 
button3.Location = new Point(shuffle[2], 250); 
+1

我們需要看看你遇到了什麼異常。 – Thor

回答

1

可以循環上的按鈕,而不是數字,如:

var buttons = new List<Button>(){button1, button2, button3}; 
i = 0; 
foreach (var button in buttons) 
{ 
    button.Location = new Point(shuffle[i], 250); 
    button.Text = text[i]; 
    i++; 
    } 

然後你就可以添加所有的按鈕,列表和循環直通它們。