Oso
Oso

Reputation: 13

One Button To Toggle Form's BackGround Color

I am a novice in C# WindowForm projects, and I am facing some issues on how to toggle 'one button' into changing between 2 backcolors in C# WindowForm.

In order to toggle 'one button', I am required to use IF function in this assignment. However, my problem is that I do not know how to transition from color1 to 2 by pressing the button when running the code, I somewhat know the syntax structure of IF and else.

Could anyone help please?

namespace draft
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void btn1_Click(object sender, EventArgs e)
    {
      bool btnclick = true;
      if (btnclick == true)
      {
        BackColor = Color.Purple;
        return;
      }
      if (btnclick == false)
      {
        BackColor = Color.Green;
        return;
      }
    }
  }
}

Upvotes: 0

Views: 1297

Answers (2)

Enigmativity
Enigmativity

Reputation: 117019

Here's the simplest code:

private void btn1_Click(object sender, EventArgs e)
{
    BackColor = BackColor == Color.Purple ? Color.Green : Color.Purple;
}

Upvotes: 0

Sailesh Babu Doppalapudi
Sailesh Babu Doppalapudi

Reputation: 1544

As you are declaring btnclick on click event and setting it to true, it will be true every time and only if block will be executed. Check current background color and change it.

private void btn1_Click(object sender, EventArgs e)
    {
        if (BackColor == Color.Purple)
        {
            BackColor = Color.Green;
            return;
        }
        else
        {
            BackColor = Color.Purple;
            return;
        }
    }

Upvotes: 1

Related Questions