0

I need to change the button background color by itself, that means when I will click on a button then it should change the background color, but when I will click again on the same button then I need to back default button color

I have tried on this event method

private void slot_1(object sender, RoutedEventArgs e)
{
    //SlotLogic();
    slot1.Background = Brushes.Green;
}

private void slot_2(object sender, RoutedEventArgs e)
{
    //SlotLogic();
    slot2.Background = Brushes.Green;
}
1
  • What is happening and what did you expect to happen? Commented Dec 14, 2020 at 8:21

1 Answer 1

1

1 - You specified Windows Application. That's kind of broad. I believe you mean Windows Forms?

2 - You're also not checking whatsoever the current state of the button, so I'm not sure how do you think that clicking on the same button twice would have a different result, since you are executing the exact same come twice slot1.Background = Brushes.Green;.

Windows Forms

private bool isSlot_1Clicked = false;
private void slot_Click(object sender, EventArgs e)
{
    if (isSlot_1Clicked)
        slot.BackColor = Color.Green;

    else
        slot.BackColor = Color.Red;

    isSlot_1Clicked = !isSlot_1Clicked;
}

If you want to have a toggle logic, you need to check the current state to inverse it. There is a lot of ways to do it, I choose to store it on a separate variable isSlot_1Clicked for sake of simplicity.

You could also check the slot's button background color, or check a complex object's property, or an array, and so on.

The first lines of code just checks the current state of the variable, and changes the button's background accordingly. The last line just set the variable isSlot_1Clicked to the inverse of it, executing the essence of the toggle logic.


WPF Version

private Brush slot_1DefaultBackground = null;
private void Slot1_Click(object sender, RoutedEventArgs e)
{
    // store the default background value
    if (slot_1DefaultBackground == null)
        slot_1DefaultBackground = slot1.Background;


    // check the current background, and toggle accordingly
    if (slot1.Background != slot_1DefaultBackground)
        slot1.Background = slot_1DefaultBackground;

    else
        slot1.Background = Brushes.Green;
}

This version stores the default button's background, and checks the current background against it to execute the toggle logic.

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

1 Comment

@AlaminSheikh glad I could help! welcome to the community

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.