C# 如何处理以编程方式添加的按钮事件?C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2104299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to handle programmatically added button events? c#
提问by jello
I'm making a windows forms application using C#. I add buttons and other controls programmatically at run time. I'd like to know how to handle those buttons' click events?
我正在使用 C# 制作 Windows 窗体应用程序。我在运行时以编程方式添加按钮和其他控件。我想知道如何处理这些按钮的点击事件?
回答by JaredPar
Try the following
尝试以下
Button b1 = CreateMyButton();
b1.Click += new EventHandler(this.MyButtonHandler);
...
void MyButtonHandler(object sender, EventArgs e) {
...
}
回答by SwDevMan81
Check out this example How to create 5 buttons and assign individual click events dynamically in C#
回答by jello
seems like this works, while adding a tag with each element of the array
似乎这有效,同时为数组的每个元素添加一个标签
Button button = sender as Button;
do you know of a better way?
你知道更好的方法吗?
回答by Shaokan
If you want to see what button was clicked then you can do the following once you create and assign the buttons. Considering that you create the button IDs manually:
如果您想查看点击了哪个按钮,那么您可以在创建和分配按钮后执行以下操作。考虑到您手动创建按钮 ID:
protected void btn_click(object sender, EventArgs e) {
Button btn = (Button)sender // if you're sure that the sender is button,
// otherwise check if it is null
if(btn.ID == "blablabla")
// then do whatever you want
}
You can also check them from giving a command argument to each button.
您还可以通过为每个按钮提供命令参数来检查它们。
回答by Jameel
Use this code to handle several buttons' click events:
使用此代码处理多个按钮的点击事件:
private int counter=0;
private void CreateButton_Click(object sender, EventArgs e)
{
//Create new button.
Button button = new Button();
//Set name for a button to recognize it later.
button.Name = "Butt"+counter;
// you can added other attribute here.
button.Text = "New";
button.Location = new Point(70,70);
button.Size = new Size(100, 100);
// Increase counter for adding new button later.
counter++;
// add click event to the button.
button.Click += new EventHandler(NewButton_Click);
}
// In event method.
private void NewButton_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
for (int i = 0; i < counter; i++)
{
if (btn.Name == ("Butt" + i))
{
// When find specific button do what do you want.
//Then exit from loop by break.
break;
}
}
}
回答by TehSpowage
In regards to your comment saying you'd like to know which button was clicked, you could set the .Tag attribute of a button to whatever kind of identifying string you want as it's created and use
关于您的评论说您想知道单击了哪个按钮,您可以将按钮的 .Tag 属性设置为您想要的任何类型的标识字符串,因为它被创建并使用
private void MyButtonHandler(object sender, EventArgs e)
{
string buttonClicked = (sender as Button).Tag;
}