winforms - C# Button loop? -
i'm trying figure out code i'm supposed write in accordance book (head first c#, 3.5 edition). i'm absolutely baffled loop i'm suppose write. here's i'm suppose do:
make form, have button, check box, , label. when check box marked, button suppose change background color of label. color suppose switch between red , blue when button pressed.
this current code.
namespace secondcolorchangingwindow { public partial class form1 : form { public form1() { initializecomponent(); } private void button1_click(object sender, eventargs e) { while (checkbox1.checked == false) // code stop if box isn't checked { messagebox.show("you need check box checked first!"); break;//stops infinite loop } while (checkbox1.checked == true)// code continues "if" box checked. { bool isred = false; // makes "isred" true, since background color default red. if (isred == true) // if ground color red, change blue { label1.backcolor = color.blue; // changes background color blue isred = false; //makes "isred" false next time check made, skips while loop messagebox.show("the color blue.");//stops program can see color change } if (isred == false)//if ground color blue, change red { label1.backcolor = color.red;//makes background color red isred = true;//sets "isred" true messagebox.show("the color red.");//stops program can see color change. } } } } }
right loops on red. don't understand i'm doing wrong. isn't first code i've written. i've gone integers boolean trying color change, either: makes color once , no other color. or program freezes infinite loops.
you don't need while loop, try if condition , check label color below
private void button1_click(object sender, eventargs e) { if(!checkbox1.checked) { messagebox.show("you need check box checked first!"); } else { //changes background color label1.backcolor = label1.backcolor == color.blue? color.red:color.blue; messagebox.show("the color " + label1.backcolor.tostring()); } }
in current code there no break condition if checkbox1 checked. run infinite loop , freeze program. better add break;
after each messagebox.show
lines.
Comments
Post a Comment