在面板上动态创建按钮

时间:2014-01-18 17:04:10

标签: c# winforms

在面板上动态创建按钮的方式

我试过了。

int top = 50;
int left = 100;

for (int i = 0; i < 10; i++)
{
    Button button = new Button();
    button.Left = left;
    button.Top = top;
    this.Controls.Add(button);
    top += button.Height + 2;
}

但我不知道如何将它们放在面板上

1 个答案:

答案 0 :(得分:4)

不是将按钮添加到表单控件,而是将它们添加到面板控件(我相信this是您的表单或用户控件):

int top = 50;
int left = 100;

for (int i = 0; i < 10; i++)
{
    Button button = new Button();
    button.Left = left;
    button.Top = top;
    panel.Controls.Add(button); // here
    top += button.Height + 2;
}

更新:对于处理按钮点击事件,您应该订阅单个事件处理程序的所有按钮(当您创建按钮时):

    button.Click += Button_Click;

在事件处理程序中,您可以使用sender查看按钮引发的事件:

private void Button_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;
    // you have instance of button
    // ...
}
相关问题