我正在试图找出一个我应该根据我的书写的代码(首先进入C#,3.5版)。我完全被一个我想写的循环所困惑。这就是我想要做的事情:
制作表格,按钮,复选框和标签。仅当标记了复选框时,按钮才会更改标签的背景颜色。按下按钮时,颜色可以在红色和蓝色之间切换。
这是我目前的代码。
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.
}
}
}
}
}
现在它只在红色上循环。我不明白我做错了什么。这不是我写的第一个代码。我已经从整数到布尔试图让颜色改变,但它要么:使颜色一次,而不是其他颜色。或者程序冻结,因为它无限循环。
答案 0 :(得分:7)
你不需要while循环,尝试条件并检查标签颜色如下
private void button1_Click(object sender, EventArgs e)
{
if(!checkBox1.Checked)
{
MessageBox.Show("You need the check box checked first!");
}
else
{
//changes the background color
label1.BackColor = label1.BackColor == Color.Blue? Color.Red:Color.Blue;
MessageBox.Show("The color is " + label1.BackColor.ToString());
}
}
如果checkBox1已选中,则在当前代码中没有中断条件。它将运行无限循环并冻结程序。您最好在每个break;
行之后添加MessageBox.Show
。
答案 1 :(得分:0)
您不需要两个while语句。您正在编写一个事件例程,该例程在每次单击button1时运行。只需设置属性或显示消息并返回调用此例程的“事件处理器”。
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == false) // The code will stop if the box isn't checked
{
MessageBox.Show("You need the check box checked first!");
}
else //(checkBox1.Checked == true)
{ // etc.
大多数事件例程将执行一个函数,然后返回调用者。
答案 2 :(得分:0)
你也可以这样做:
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
if (label1.BackColor == Color.Blue)
{
label1.BackColor = Color.Red;
MessageBox.Show("The color is red.");
}
else
{
label1.BackColor = Color.Blue;
MessageBox.Show("The color is blue.");
}
}
else
{
MessageBox.Show("You need the check box checked first!");
}
}