Problem with anonymouse delegate within foreach
Posted
by geting
on Stack Overflow
See other posts from Stack Overflow
or by geting
Published on 2010-04-03T13:49:56Z
Indexed on
2010/04/03
13:53 UTC
Read the original article
Hit count: 189
public Form1()
{
InitializeComponent();
Collection<Test> tests = new Collection<Test>();
tests.Add(new Test("test1"));
tests.Add(new Test("test2"));
foreach (Test test in tests)
{
Button button = new Button();
button.Text = test.name;
button.Click+=new EventHandler((object obj, EventArgs arg)=>{
this.CreateTest(test);
});
this.flowLayoutPanel1.Controls.Add(button);
}
}
public void CreateTest(Test test)
{
MessageBox.Show(test.name);
}
}
when i click the button witch text is 'test1', the messagebox will show 'test2',but my expect is 'test1'. So ,would anyone please tell me why or what`s wrong with my code.
© Stack Overflow or respective owner