I'm trying to figure out a code I'm supposed to write in accordance to my book (Head first into C#, 3.5 edition). I'm just absolutely baffled by a loop I'm suppose to write. Here's what I'm suppose to do:
Make a form, have a button, check box, and label. Only when the check box is marked, is the button suppose to change the background color of the label. The color is suppose to switch between red and blue when the button is pressed.
This is my current code.
namespace SecondColorChangingWindow
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
while (checkBox1.Checked == false) // The code will stop if the box isn't checked
{
MessageBox.Show("You need the check box checked first!");
break;//Stops the infinite loop
}
while (checkBox1.Checked == true)// The code continues "if" the box is checked.
{
bool isRed = false; // Makes "isRed" true, since the background color is default to red.
if (isRed == true) // If the back ground color is red, this will change it to blue
{
label1.BackColor = Color.Blue; // changes the background color to blue
isRed = false; //Makes "isRed" false so that the next time a check is made, it skips this while loop
MessageBox.Show("The color is blue.");//Stops the program so I can see the color change
}
if (isRed == false)//if the back ground color is blue, this will change it to red
{
label1.BackColor = Color.Red;//Makes the background color red
isRed = true;//Sets the "isRed" to true
MessageBox.Show("The color is red.");//Stops the program so I can see the color change.
}
}
}
}
}
Right now it only loops on red. I don't understand what I'm doing wrong. This isn't the first code I've written. I've gone from integers to Boolean trying to get the color to change, but it either: makes the color once and no other color. Or the program freezes as it infinite loops.