Skip to main content
 首页 » 编程设计

c#之在面板上动态创建按钮

2024年02月13日11lidabo

查看在面板上动态创建按钮的方法

我试过了。

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

但是我不知道怎么把它们放在面板上

请您参考如下方法:

不是将按钮添加到表单控件,而是将它们添加到面板控件(我相信 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 
    // ... 
}