Assuming you want the Button to continue switching colors with every Click, and that you do not need to preserve the original Form BackColor on start-up:
Color firstColor = Color.Red;
Color secondColor = Color.Green
bool whichColor = true;
private void btn_Click(Object s, EventArgs e)
{
BackColor = whichColor ? firstColor : secondColor;
whichColor = ! whichColor;
}
Or, you could simplify this to:
private void button1_Click(object sender, EventArgs e)
{
BackColor = (whichColor = ! whichColor) ? firstColor : secondColor;
}
You could simplify even further if you are sure you don't need access to the created Button outside the scope/context in which it was created at run-time:
private void SomeForm_Load(object sender, EventArgs e)
{
Button newButton = new Button();
newButton.AutoSize = true;
newButton.Location = new Point(400, 100);
newButton.Text = "Click to Change Form Background Color";
newButton.ForeColor = Color.White;
newButton.Click += (obj, eArgs) =>
{
BackColor = (BackColor == Color.Red) ? Color.Green: Color.Red;
};
Controls.Add(newButton);
}
Note the interesting fact that if the Control you create, as a child Control of a Form, does not have its BackColor, set when you create it at run-time, it will "inherit" the BackGround Color of the Form, and as the form BackColor is changed, the Button will change BackGround Color also: I have never seen this behavior "officially" described by Microsoft !
But, that behavior was exactly why I set the ForeColor property of the Button to white: so that it would be visible whether the Button BackColor was red, or green :)