I will create dynamic buttons in C# and I need to add a parameter to the Click-Event-Handler (ID).
But, in this exmaple the output is allways the last parameter “10” for ALL buttons, and not “1-2-3-4-5-….”, why?
for(int counter = 1; counter < 10; counter++)
{
// Add new button
Button btn = new Button();
btn.Width = 250;
btn.Height = 50;
btn.Click += delegate (object sender1, EventArgs e1)
{ myEventHandler(sender1, e1, counter); };
Test.Controls.Add(btn);
}
public void myEventHandler(object sender, EventArgs e, int i)
{
MessageBox.Show("Test: " + i);
}
Thanx for any help!
Florian
This is because the counter variable is not captured. This means that when the loop finishes the value of counter will be 10, so all delegates will have that value to fix you can use a variable within the loop like this:
See this question on stackoverflow for more info Captured variable in a loop in C#