【问题标题】:delegate method inside foreach loop always binds to last item [duplicate]foreach 循环中的委托方法始终绑定到最后一项
【发布时间】:2012-07-16 11:52:01
【问题描述】:

可能重复:
C#: using the iterator variable of foreach loop in a lambda expression - why fails?

我有一个向自定义控件添加一些按钮的方法。我希望每个按钮都有一个事件处理程序,它将弹出一个消息框以显示有关该按钮的详细信息。

我编写了下面的代码,但是我添加的所有按钮都将显示有关List<Pin>....中最后一个按钮的详细信息。如何为每个按钮及其各自的pin 对象添加点击事件hadnler?

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

【问题讨论】:

    标签: c# winforms events delegates foreach


    【解决方案1】:
    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;
    };
    

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多