4

How do I use one individual event handler per iteration, without hard coding the functions?

for (int i = 0; i < 100; i++)
{
        //other code
        PictureBox listItem = new PictureBox();
        listItem.Click += new EventHandler((sender2, e2) => ListItemClicked(i));
        //other code     
}

private void ListItemClicked(int index)
{
    MessageBox.Show(index.ToString());
}
Reese
  • 253
  • 5
  • 15

1 Answers1

5

You need to copy your iterator into a local variable for the delegate to capture it correctly:

for (int i = 0; i < 100; i++)
{
        var idx = i;
        //other code
        PictureBox listItem = new PictureBox();
        listItem.Click += new EventHandler((sender2, e2) => ListItemClicked(idx));
        //other code     
}

In you original piece of code, the delegate says "return me the current value of the variable", which is 100. Not: "the value when it was created". Read up on closures to get an in depth explanation of this. I'd recommend Jon Skeets C# in depth.

In c# 5.0 this was changed for the foreach loop, not the for i; one though.

Marco
  • 22,856
  • 9
  • 75
  • 124