我正在试图找出一个我应该根据我的书写的代码(首先进入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.
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在它只在红色上循环.我不明白我做错了什么.这不是我写的第一个代码.我已经从整数到布尔试图让颜色改变,但它要么:使颜色一次,而不是其他颜色.或者程序冻结,因为它无限循环.
你不需要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());
}
}
Run Code Online (Sandbox Code Playgroud)
如果checkBox1已选中,则在当前代码中没有中断条件.它将运行无限循环并冻结程序.你最好break;在每一MessageBox.Show行之后添加.
| 归档时间: |
|
| 查看次数: |
513 次 |
| 最近记录: |