I have a Button array in C# WFA and I want to create an event for a click of any button in the array. How can I do it? And how to know which location in the array it is? I know sender is the button itself
3 Answers
You can use a for loop that closes over a variable containing the current index:
for(int i = 0; i < buttons.Length; i++)
{
//it's important to have this; closing over the loop variable would be bad
int index = i;
buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
2 Comments
user2390564
Thank you.I just want to know, what is the last row? I know what its doing, just want to know how does it called so i can learn it.
Servy
It is creating an anonymous method; this particular syntax is called a lambda expression.
try this
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Button[] myButtons = new Button[10];
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 0; i < myButtons.Length; i++)
{
int index = i;
this.myButtons[i] = new Button();
this.myButtons[i].Location = new System.Drawing.Point(((i + 1) * 70), 100 + ((i + 10) * 5));
this.myButtons[i].Name = "button" + (index + 1);
this.myButtons[i].Size = new System.Drawing.Size(70, 23);
this.myButtons[i].TabIndex = i;
this.myButtons[i].Text = "button" + (index + 1);
this.myButtons[i].UseVisualStyleBackColor = true;
this.myButtons[i].Visible = true;
myButtons[i].Click += (sender1, ex) => this.Display(index+1);
this.Controls.Add(myButtons[i]);
}
}
public void Display(int i)
{
MessageBox.Show("Button No " + i);
}
}
}