Yup - you close the loop variable. test in the lambda expression refers to the same variable in all your delegates, which means that the final value will be completed at the end of the loop. Take a copy of the value and use it. You also use a rather long form of lambda expression. Here's a fixed and shortened code:
foreach (Test test in tests) { // Take a copy of the "test" variable so that each iteration // creates a delegate capturing a different variable (and hence a // different value) Test copy = test; Button button = new Button(); button.Text = test.name; button.Click += (obj, arg) => CreateTest(copy); this.flowLayoutPanel1.Controls.Add(button); }
For more information see Eric Lippert's blog post .
source share