delegate method inside foreach loop always binds t

2019-07-25 12:43发布

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);
        }
    }

1条回答
Deceive 欺骗
2楼-- · 2019-07-25 13:09
button.Tag = pin;
button.Click += MyHandler;

void MyHandler(object sender, EventArgs e)
{
    var pin = (Pin)sender.Tag;
}

Or as a lambda:

button.Tag = pin;
button.Click += (s, e) =>
{
    var pin = (Pin)s.Tag;
};
查看更多
登录 后发表回答