如何在for循环中添加buttonlocation?

时间:2017-04-05 15:02:19

标签: c# winforms

我尝试在Windows窗体中的随机位置放置一些按钮,如下所示:

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 个答案:

答案 0 :(得分: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++;
    }

然后,您可以将所有按钮添加到列表中并循环播放。