C# label color change

32,655

Solution 1

3 labels which show the total calorie count, it means that they changed. You may use TextChanged event on label (in form designer press F4 and go to events menu).

private void label1_TextChanged( object sender, EventArgs e )
    {
        if ( this._calories < 0 )
        {
            this.lb_Main.BackColor = Color.Red;
        }
        else
        {
            this.lb_Main.BackColor = Color.Green;
        }
    }

Solution 2

To change a background color of a control, it is enough to set its BackColor property to a color, System.Drawing.Color.Red for example.

For example in your case:

if (calori > 0)
    label1.BackColor = System.Drawing.Color.Green;
else
    label1.BackColor = System.Drawing.Color.Red;

Or:

label1.BackColor = (calori > 0) ? System.Drawing.Color.Green : System.Drawing.Color.Red;

Solution 3

calorieCountLabel.BackColor = calories.Count > 0 ? Color.green : Color.red
Share:
32,655
ritik
Author by

ritik

Updated on December 26, 2020

Comments

  • ritik
    ritik over 3 years

    So I am building a very basic calorie counter. I have 3 labels which show the total calorie count, one that shows the last amount of calories I had, and one that shows the number of items i have ate.

    There are 3 that add calories, and 3 that reduce the calories. so I was wondering how I would do this:

    If the calories are above 0, the backcolor should become green, and if it is below 0, the back color should be red. I know that this is not a lot of info, and I apologize for that. I am a noob, but that is no excuse. Thank you for the help!