0

I have the code below.

public void WepaonEquip(Object sender, System.EventArgs e)
{
if (button[0].BackColor == Color.Beige)
{
    button[0].BackColor = Color.OrangeRed;
}

else if (button[1].BackColor == Color.Beige)
{
    button[1].BackColor = Color.OrangeRed;
}

else if (button[2].BackColor == Color.Beige)
{
    button[2].BackColor = Color.OrangeRed;
}
}

The code in the class containing this chunk of code generates a button array. What I want is that the user will click a button and the colour of the button clicked will change.

However, when the user clicks, lets say, the 3rd button, the first button in the array changes colour, not the one clicked. Any idea as to why this isn't working? I believe the logic of the code works, perhaps I'm missing something.

1 Answer 1

3

Set each button in the panel to use the same Click Event handler. In the handler cast sender as a button and change the color

Assuming that WeaponEquip is the click event handler for the buttons it would look something like this:

public void WepaonEquip(Object sender, System.EventArgs e)
{
    Button clickedbutton = (Button)sender
    clickedbutton.BackColor = Color.OrangeRed;

}
Sign up to request clarification or add additional context in comments.

4 Comments

sorry, panel1 is irrelevent, ill take that off
That's fine, the concept will still work with whichever buttons you want to handle.
alright, i added them into one click event, but nothing changed, see above for edited code
@user3170251 You do not need to use conditional logic to test for every button, the sender is the button that was clicked, just do what tinstaafl said and cast it to a button then test your color.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.