I use the loop for a two dimensions array of buttons. I don't know how to know exactly which buttons in array were clicked or not
Here are my code:
for (int i = 0; i < 100 ; i++)
{
for (int j=0 ; j< 100; i++)
{
arrButton[i, j] = new Button();
arrButton[i,j].Size = new Size(size1button, size1button);
arrButton[i,j].Location = new Point(j*size1button, i*size1button);
arrButton.Click += new EventHandler(arrButton_Click);
}
}
Can I use parameters i, j for mouse click event like:
private void arrButton_Click(object sender, EventArgs e, int i, int j)
{
//my idea : add i, j to another int[,] array to keep track of buttons which were clicked
}
If this exits, how to write it correctly? Or can you recommend or method to know exactly where the button was clicked in array ?
Try this
Now in loop set Tag
Get values from Tag here as
You cannot change the EventHandler signature to include your
i
andj
.However, you can get that information from what is already passed to the
arrButton_Click
method. Since you set the location of each button asnew Point(j*size1button, i*size1button)
, you can get eachi
andj
component back by dividing the location of your button bysize1button
.To get that location, you can use the
sender
, which is yourButton
(a cast is necessary):Also, the code you're currently using to create the buttons have a couple errors.
First, you're never incrementing
j
; the second loop doesi++
.Second, if you want your buttons to appear, you have to add them to your Form's
Controls
.Finally, I don't think you can have 10 000 active buttons on your form, try a lower number, like 25.
So the corrected code would look like:
You can also notice that I removed your declaration of
new EventHandler
, which was redundant.If you are only interested in
Location
then whats wrong with this? -But if you want more data other than just location. Here is an example
Use a custom button class -
Then use this button class -
In the event handler
Cast
toCustomButton
and voila, there is your location -BTW, you cannot change the default signature of event handlers, if you want you have to implement your own event/delegate.