3
votes

How can I create a program in C# that does the following: 1. Create a WindowsForm with a button and a label 2. When the button is pressed the label should change from "False" to "True" or vice-versa

I want the label's message to be displayed depending on the state of a boolean variable.

bool Light1 = false;

When I press the button, I want Light1 to become True and if I press it again it should become False.

The label shows a True or False message depending on Light1;

The problem I am facing is changing the label depending on Light1. The code that gets executed when I press the button is:

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 Light1 variable that is initialized to False.

I would be grateful if someone could explain to me how I could make the connection between a label and the Light1 variable.

2
If you're just getting into C#, you should work on learning WPF and MVVM for UI related development. - Jordan Kaye
@JordanKaye I think MVVM might be a bit too complicated when OP hasn't had much experience with C#. - keyboardP
@keyboardP Learning in the wrong way in the first place is only going to complicate things down the road. Better to do things right the first time. - Jordan Kaye
@JordanKaye I disagree. I think you should have a grasp of the language first before worrying about learning patterns. I agree MVVM is a good pattern, but only if the project is suited to it. It's not as black and white as the "right way" and the "wrong way" IMHO. - keyboardP

2 Answers

4
votes
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 letter in uppercase (True, False), just do that:

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);
}
2
votes

You can set the bool value in a label by the Text property:

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();
}