I'm creating an array of controls and adding them to the form, and setting their events to a function that receives the index of the clicked button using a lambda expression (b.Click += (sender, e) => myClick(i);
).
But the problem is... Whichever you click on, you receive the index 100, not the real index of the button! What is the problem here?
namespace testArrayOfControls
{
public partial class Form1 : Form
{
Button[] buttons;
public Form1()
{
InitializeComponent();
buttons = new Button[100];
for (int i = 0; i < 100; i++)
{
buttons[i] = new Button();
buttons[i].SetBounds(i % 10 * 50, i / 10 * 50, 50, 50);
buttons[i].Click += (sender, e) => myClick(i);
this.Controls.Add(buttons[i]);
}
}
private void myClick(int i)
{
MessageBox.Show(i.ToString());
}
}
}