2017-04-05 79 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++; 
    } 

然后你就可以添加所有的按钮,列表和循环直通它们。