foreach循环中的委托方法总是绑定到最后一个项目 [英] delegate method inside foreach loop always binds to last item
本文介绍了foreach循环中的委托方法总是绑定到最后一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法可以为自定义控件添加一些按钮。我想要每个按钮都有一个事件处理程序,它将弹出一个消息框,以显示该按钮的详细信息。
I have a method that adds some buttons to a custom control. I want each button to have an event handler which will pop up a message box to show details about that button.
我在下面写了代码,但是所有的按钮添加将显示关于列表< Pin>
....中的最后一个按钮的详细信息....如何为每个按钮添加点击事件,其各自的 pin
object?
I wrote the code below, but all the buttons that I add will show details about the last button in the List<Pin>
....How can I add click event hadnler for each button with its respective pin
object?
public void Populate(List<Pin> pins)
{
_pins = pins;
var count = _pins.Count;
var location = new Point(5, 5);
foreach (var pin in _pins)
{
var button = new Button();
button.Text = pin.Name;
button.Name = "buttonPin_" + pin.Name;
button.Click += delegate
{
MessageBox.Show(pin.Name + Environment.NewLine + pin.Batch);
};
button.Size = new Size(30, 30);
button.Location = location;
location.X += 30;
if (location.X > Width) location = new Point(5, location.Y + 35);
Controls.Add(button);
}
}
推荐答案
button.Tag = pin;
button.Click += MyHandler;
void MyHandler(object sender, EventArgs e)
{
var pin = (Pin)sender.Tag;
}
或作为lambda:
button.Tag = pin;
button.Click += (s, e) =>
{
var pin = (Pin)s.Tag;
};
这篇关于foreach循环中的委托方法总是绑定到最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文