C# 如何创建 5 个按钮并动态分配单个点击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1434282/
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 do I create 5 buttons and assign individual click events dynamically?
提问by Rajkishor Sahu
I need to create 5 buttons dynamically on windows form and each button should respond to click event. I tried it but all buttons are responding to same event.
我需要在 Windows 窗体上动态创建 5 个按钮,每个按钮都应响应单击事件。我试过了,但所有按钮都响应相同的事件。
采纳答案by SwDevMan81
This is what Nick is talking about are your two options (You should be able to run this code and see both options):
这就是 Nick 正在谈论的是您的两个选项(您应该能够运行此代码并看到两个选项):
public Form1()
{
InitializeComponent();
for (int i = 0; i < 5; i++)
{
Button button = new Button();
button.Location = new Point(20, 30 * i + 10);
switch (i)
{
case 0:
button.Click += new EventHandler(ButtonClick);
break;
case 1:
button.Click += new EventHandler(ButtonClick2);
break;
//...
}
this.Controls.Add(button);
}
for (int i = 0; i < 5; i++)
{
Button button = new Button();
button.Location = new Point(160, 30 * i + 10);
button.Click += new EventHandler(ButtonClickOneEvent);
button.Tag = i;
this.Controls.Add(button);
}
}
void ButtonClick(object sender, EventArgs e)
{
// First Button Clicked
}
void ButtonClick2(object sender, EventArgs e)
{
// Second Button Clicked
}
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
// now you know the button that was clicked
switch ((int)button.Tag)
{
case 0:
// First Button Clicked
break;
case 1:
// Second Button Clicked
break;
// ...
}
}
}
回答by Dario
Guessing what you might have tried: Yes, all buttons fire their events to the same method, but the sender
-parameter of your callback method contains a reference to the button that actually caused the specific event.
猜猜您可能尝试过什么:是的,所有按钮都将它们的事件触发到相同的方法,但是sender
回调方法的-parameter 包含对实际导致特定事件的按钮的引用。
回答by Nick
I assume you're in a loop and do something like this?
我假设你在一个循环中并做这样的事情?
Button newButton = new Button();
newButton.Click += new EventHandler(newButton_Clicked);
You're registering the same method for all buttons. You'll need individual methods for each button. Alternatively, you can assign each button a different identifying property and in your handler, check to see which button was the sender.
您正在为所有按钮注册相同的方法。每个按钮都需要单独的方法。或者,您可以为每个按钮分配不同的标识属性,并在处理程序中检查哪个按钮是发送者。
From there you can take appropriate action.
从那里你可以采取适当的行动。
回答by kifle
button b =new button ();
b.text = " enter text";
b.click =+(then press Tab using key board)