gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:37:01 24 4
gpt4 key购买 nike

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

我试过了。

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
// ...
}

关于c# - 在面板上动态创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21207130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com