Here's some sample code which denotes my problem. It adds 5 LinkLabel
s, each with a Click
event handler. The text on the label is 1...5 and should display the same result when clicked, but when I click on each of the labels I get the same message for each: 5.
It's like the last handler is overwriting the handler on each of the other labels. I thought I had avoided that by creating a new EventHandler
and new LinkLabel
each iteration of the loop.
I added each LinkLabel
to a FlowLayoutPanel
.
Why am I getting this result, and how can I fix it?
List<Test> objects = new List<Test>();
for (int i = 0; i < 5; i++)
{
objects.Add(new Test(i + 1));
}
foreach (Test t in objects)
{
LinkLabel label = new LinkLabel();
label.AutoSize = true;
label.Text = t.a + "";
label.Click += new EventHandler((sender, args) =>
{
MessageBox.Show(t.a + "");
});
flowLayoutPanel1.Controls.Add(label);
}