Possible Duplicate:
C#: using the iterator variable of foreach loop in a lambda expression - why fails?
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.
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);
}
}
Or as a lambda: