如何创建5个按钮和动态分配各个单击事件? [英] How do I create 5 buttons and assign individual click events dynamically?
本文介绍了如何创建5个按钮和动态分配各个单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要建立动态的5个按钮的Windows窗体,每个按钮应该响应单击事件。我尝试过,但所有的按钮都响应相同的事件。
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.
推荐答案
这就是尼克讲的是两个选择(你应该能够运行这个code,看到这两个选项):
This is what Nick is talking about are your two options (You should be able to run this code and see both options):
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;
// ...
}
}
}
这篇关于如何创建5个按钮和动态分配各个单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文