C#按钮循环?
发布时间:2020-12-16 01:56:40 所属栏目:百科 来源:网络整理
导读:我正在试图找出一个我应该根据我的书写的代码(首先进入C#,3.5版).我完全被一个我想写的循环所困惑.这是我想要做的: 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 co
我正在试图找出一个我应该根据我的书写的代码(首先进入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. } } } } } 现在它只在红色上循环.我不明白我做错了什么.这不是我写的第一个代码.我已经从整数到布尔试图让颜色改变,但它要么:使颜色一次,而不是其他颜色.或者程序冻结,因为它无限循环. 解决方法
你不需要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已选中,则在当前代码中没有中断条件.它将运行无限循环并冻结程序.你最好添加休息;在每个MessageBox.Show行之后. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |