title: Closures in C# event handler delegates?
body: <p>I am coming from a functional-programming background at the moment, so forgive me if I do not understand closures in C#.</p>
  
  <p>I have the following code to dynamically generate Buttons that get anonymous event handlers:</p>
  
  <pre><code>for (int i = 0; i &lt; 7; i++)
  {
      Button newButton = new Button();
  
      newButton.Text = "Click me!";
  
      newButton.Click += delegate(Object sender, EventArgs e)
      {
          MessageBox.Show("I am button number " + i);
      };
  
      this.Controls.Add(newButton);
  }
  </code></pre>
  
  <p>I expected the text <code>"I am button number " + i</code> to be closed with the value of <code>i</code> at that iteration of the for loop.  However, when I actually run the program, every Button says <code>I am button number 7</code>.  What am I missing? I am using VS2005.</p>
  
  <p>Edit: So I guess my next question is, how do I capture the value?</p>