[英]Define function to dynamically created buttons
I want to create 5 buttons in a for loop and assign a different function to each one dynamically. 我想在for循环中创建5个按钮,然后为每个按钮动态分配一个不同的功能。 For example, first button to show a message 1, ... , and the 5th to show 5.
例如,第一个按钮显示消息1,...,第五个按钮显示消息5。
Here is the sample code: 这是示例代码:
private void Form1_Load(object sender, EventArgs e)
{
var left = 10;
for(int i= 0; i< 5; i++)
{
var btn = new Button();
btn.Text = i.ToString();
btn.Width = 50;
btn.Height = 50;
btn.Left = left;
btn.Height = 50;
left += 55;
btn.Click += (s2, e2) => btn_Click(s2, e2, i.ToString());
this.Controls.Add(btn);
}
}
static void btn_Click(object sender, EventArgs e, string s)
{
MessageBox.Show(s);
}
But all buttons print 5. How can I differentiate functions of buttons? 但是所有按钮都可以打印5.如何区分按钮的功能?
var value = i.ToString();
btn.Click += (s2, e2) => btn_Click(s2, e2, value);
this.Controls.Add(btn);
Read more about clousure capture . 阅读有关clousure捕获的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.