0

I want to create 5 buttons in a for loop and assign a different function to each one dynamically. For example, first button to show a message 1, ... , and the 5th to show 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?

Mika Sundland
  • 18,120
  • 16
  • 38
  • 50

1 Answers1

1
var value = i.ToString();
btn.Click += (s2, e2) => btn_Click(s2, e2, value);
this.Controls.Add(btn);

Read more about clousure capture.

Backs
  • 24,430
  • 5
  • 58
  • 85