C # execute methods in the form
How to create a C # program that does the following: 1. Create a WindowsForm with a button and a label 2. When the button is clicked, the label should change from "False" to "True" or vice versa
I want the label message to be displayed based on the state of a boolean variable.
bool Light1 = false;
When I click the button, I want it to Light1
become True, and if I click it again, it becomes False.
The label displays True or False depending on Light1
;
The problem I am facing is changing the label depending on Light1
. Code that runs when the button is clicked:
private void button1_Click(object sender, EventArgs e)
{
if (parametri.Light1 == false)
{
parametri.Light1 = true;
}
else
{
parametri.Light1 = false;
}
}
parametri
is a class that contains one public bool variable Light1
that is initialized to False.
I would appreciate it if someone could explain to me how I can establish the relationship between the label and the Light1 variable.
source to share
private void button1_Click(object sender, EventArgs e)
{
// No need of IF Statements to reverse a Boolean
parametri.Light1 = !parametri.Light1;
label1.Text = parametri.Light1.ToString();
}
If you want to have the first uppercase letter (True, False), just do this:
private void button1_Click(object sender, EventArgs e)
{
// No need of IF Statements to reverse a Boolean
parametri.Light1 = !parametri.Light1;
Char[] characters = parametri.Light1.ToString().ToCharArray();
characters[0] = Char.ToUpper(characters[0]);
label1.Text = new String(characters);
}
source to share
You can set the bool value in the label using the property Text
:
private void button1_Click(object sender, EventArgs e)
{
// invert the bool value with the not operator. In C# is equals Java "!"
parametri.Light1 == !parametri.Light1;
// print the bool value in your label.
Label1.Text = parametri.Light1.ToString();
}
source to share