toggle ON and OFF button


1
2
3
4
5
6
7
8
9
10
11
12
13
void button1{
bool x = false;
					 
if (x = true)
{
 button1->Text = "ON";
}
else
{
button1->Text = "OFF";					 
}
x = !x;
}


it can turn it ON when i clicked it but it doesnt turning back OFF when i clicked it again
any help pls...thanks in advance

btw the default Text is "OFF"
Last edited on
ok i just got it working..

1
2
3
4
5
6
7
8
9
10
11
12
static bool x = false;
	 
if (x == true)
{
 button1->Text = "ON";
}
 else
{
button1->Text = "OFF";
					 
}
x = !x;
Last edited on
You are declaring a variable at the beginning to be false, then checking to see if the value is either false or true. But since the value is always assigned the value false at the beginning, it can never enter the else control section so the button is always "on".

Try using a static variable instead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

void button1()
{

static bool Enabled = false;

if(Enabled)
{
    button1->Text = "On";
}
else
{
    button1->Text = "Off";
}

}


Usually after the code goes out of scope all local variables that are declared within that scope are released to the operating system. A static variable does not, and stays persistent even after the scope resolves. By using a static variable here, you can achieve the result you were looking for, which was storing the state of the variable to compare it against the previous state.

Topic archived. No new replies allowed.