i'm attempting to hook EventHandler onto object created dynamically. In this sample, i use simple windows .Net TabControl to contain the dynamic object. For simplicity i use Button and its Click event. The main point is button click on each TabPage should produce different output.
public partial class Form1 : Form
{
int letter = 65;
private void simpleButton1_Click(object sender, EventArgs e)
{
TabPage newPage = new TabPage();
tabControl1.TabPages.Add(newPage);
Button btn = new Button();
newPage.Controls.Add(btn);
btn.Click += (object s, EventArgs ee) =>
{
// Button on FirstPage should produce "Test A"
// Button on SecondPage should produce "Test B"
Debug.WriteLine("Test " + (char)letter);
};
letter++;
}
}
However, whichever button i clicked on any page produce the output of the last page (i.e. 4 TabPages, all buttons click produce "Test D"). It felt as if the reference pointer Button btn points to all instances of button on every page.
My assumption:
Button btn = new Button();
Won't the pointer btn points to new instance of Button each time this line execute? in that sense:
btn.Click += (object s, EventArgs ee) =>
The btn.Click supposed to be the EventHandler for newly created instance of Button, right? It seems as if the pointer btn still refer to all instances of Button.
Please do enlighten me on this matter. Thank you in advance.