Reputation: 55
I'm working on a game for a University assignment and need to perform an action if a button is clicked, but it's more complicated than that.
I've created a 2D array of 100 buttons (10x10) to create a tiled, clickable interface (this is a requirement of the project brief so I absolutely cannot change this method). Each button is randomly assigned a specific BackgroundImage to make up an adventure map (grass, water, trees, ore, etc.), and if they have a certain BackgroundImage and are clicked (trees or ore) I need to add Gold to the Player's gold value for them 'gathering' the item.
The array of buttons is being generated as so:
Button[,] btn = new Button[10, 10];
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((x * 50) + 8, (y * 50) + 16, 50, 50);
btn[x, y].Name = x + "," + y;
Controls.Add(btn[x, y]);
}
}
How would I be able to detect when one of these buttons is clicked and be able to act accordingly depending on what the BackgroundImage applied to it is?
Upvotes: 1
Views: 1716
Reputation: 7097
Register an OnClick event to ALL of the buttons in the array. Then cast the object sender
parameter to a button object and find out what Background Image was on that button and handle accordingly.
In the loop: btn[x, y].Click += ButtonAction_OnClick;
Handler:
private void ButtonAction_OnClick(object sender, EventArgs e)
{
Button button = sender as Button;
Image bImage = button.BackgroundImage;
if(bImage.Tag.Equals(...))
{
//do something
}
else //do something else
}
Upvotes: 1
Reputation: 11607
Add the click event:
btn.Click += clickHandler;
Then implement the click handler:
void clickHandler(object sender, EventArgs e)
{
((Button)sender).Background = Brushes.LightBlue;
}
Upvotes: 0
Reputation: 10386
One of the options available - is to assign a common event handler for all the buttons and mark every button with its kind of background (for example, in tag). Then in that handler you can check the type of button clicked and proceed as needed:
btn[x, y].Click += btnClick;
btn[x, y].Tag = "..."; //Based on background
public void btnClick(object sender, EventArgs e)
{
Button myButton = sender as Button;
if (myButton.Tag == "Mountain")
{ ... }
else if (myButton.Tag == "Forest")
{ ... }
}
Upvotes: 2
Reputation: 101701
You can attach same event handler to your all buttons like this:
btn[x, y].Click += btnClick;
And, in your btnClick
you can get your clicked button and you can do whatever you want:
public void btnClick(object sender, EventArgs e)
{
Button myButton = sender as Button;
myButton.BackgroundImage = ...
}
Upvotes: 2