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?

1 Answer 1

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

Read more about clousure capture.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.