I have this chunk of code...
public void initButtons(CheckBox[,] buttons)
{
int locX = 0;
int locY = 0;
for(int x = 0; x < buttons.GetLength(0); x++)
{
for(int y = 0; y < buttons.GetLength(1); y++)
{
buttons[x, y] = new CheckBox();
buttons[x, y].Appearance = Appearance.Button;
buttons[x, y].Location = new Point(locX, locY);
buttons[x, y].Size = new Size(60, 60);
buttons[x, y].Click += new EventHandler(this.MemoryButton_Clicked);
this.Controls.Add(buttons[x, y]);
locX += 60;
}
locX = 0;
locY += 60;
}
}
...which creates a 5x5 grid of checkboxes. I would like each individual button to have a different EventHandler (instead of all buttons sharing the same one). Is this possible?
You can use a lambda expression to make an anonymous function your event handler
buttons[x, y].Click += new EventHandler((s, ea) =>
{
//insert code here;
});
Doing this uses closures, so you can do neat things like the following.
buttons[x, y].Click += new EventHandler((s, ea) =>
{
var aString = String.Format("my coordinates are {0} and {1}", x, y);
});
Okay so i fixed it. Basically i just add buttons[x,y].Name="Button"+i; and i++; in the forloop. Each element in the 2d array gets a unique name and i can use .Name.Equals later if i want to call it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.