Reputation: 812
I have a matrix of custom buttons (class FifteenButton I made that inherits Button). I want to have a click event for each button in the matrix that calls a method that does some work. But I don't want to write such method for each button in the matrix. So, I did something like this in initializeComponent
:
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
fbarr[i, j].Click += new System.EventHandler(this.FifteenButton_Click);
and in FifteenButton_Click
I want to know which button was clicked (preferrably i, j coordinates).
How should I go about doing something like that? Maybe in the EventArgs of FifteenButton_Click
? But I have no idea how to do that.
Upvotes: 1
Views: 2292
Reputation: 216243
The event hadler of the Click event receives two parameters
void FifteenButton_Click(object sender, EventArgs e)
The sender parameter is the reference to the button clicked, so
void FifteenButton_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if(btn != null)
{
Console.WriteLine("Button clicked: " + btn.Text);
}
}
However, if you want to retrieve the location of the button in the array used in your question, you need something more. For example you could use the Tag property to store the i j coordinates of the button.
for(int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
fbarr[i, j].Click += new System.EventHandler(this.FifteenButton_Click);
fbarr[i, j].Tag = i.ToString() + "_" + j.ToString();
}
}
Now, in the event handler, you culd easily read the Tag property of the button and recover the indexes
void FifteenButton_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if(btn != null)
{
string[] xy = btn.Tag.ToString().Split('_');
Console.WriteLine("Button clicked: " + xy[0] + "," + xy[1]);
}
}
Upvotes: 2