Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

16 Sep 2006

Anonymous methods

Suppose you add a couple of buttons to a panel as shown below. What do you think the message in the MessageBoxes will be?

public partial class Form1 : Form 
{
	public Form1() 
	{
		InitializeComponent();

		for (int i = 0; i < 10; ++i) 
		{ 
			Button button = new Button(); 
			button.Text = String.Format("{0:00}", i); 
			this.flowLayoutPanel1.Controls.Add( button ); 
			button.Click += new EventHandler(delegate(Object sender, EventArgs e) 
			{ 
				MessageBox.Show(String.Format("You clicked button {0:00}", i)); 
			}); 
		} 
	} 
}

In case you’re wondering why they all have the message “You clicked button 10” i suggest you read the following articles