Search code examples
c#colorstrackbar

C# Changing color of label based on trackbar value


I am working with a trackbar that has a value of 0 to 100. In my code automatic = 0 that you see in the image below.

What i am trying to accomplish is that any number below 35 should change the labels (lableFS) forcolor to red, while any number above that should change the labels forecolor to green. I have that working fine, however the exception here should be that if the value of the trackbar is 0 or even if the labelFS text is set to "Automatic", then the labelFS forecolor should be black. Below is a gif image that will show you exactly what i mean, as well as my current code.

Thank you in advance for any help!

Demonstration of my app

I know its a simple issue, however i have tried numerous ways and i cant seem to find what is stopping it from changing to black.

        private void fanSlider_Scroll(object sender, EventArgs e)
    {
        lblFS.Text = "" + fanSlider.Value * 5;

        if (lblFS.Text == "0")
        {
            lblFS.Text = "Automatic";
        }

        int value;
        if (Int32.TryParse(lblFS.Text, out value))
        {
            if (value <= 35)
            {
                lblFS.ForeColor = System.Drawing.Color.Red;
            }
            if (value > 35)
            {
                lblFS.ForeColor = System.Drawing.Color.Green;

            }

            if (value == 0)
            {
                lblFS.ForeColor = System.Drawing.Color.Black;
            }
        }


    }

Solution

  • I think what is happening here is that whenever the bar is at 0 you set its text to Automatic, and then afterwards you try to change its color checking if its text is 0 but since you have already changed it to Automatic the condition will always be false...

    Try this:

    private void fanSlider_Scroll(object sender, EventArgs e)
    {
        lblFS.Text = "" + fanSlider.Value * 5;
        if (lblFS.Text == "0")
        {
            lblFS.Text = "Automatic";
            lblFS.ForeColor = System.Drawing.Color.Black;
        }
        int value;
        if (Int32.TryParse(lblFS.Text, out value))
        {
            if (value <= 35)
            {
                lblFS.ForeColor = System.Drawing.Color.Red;
            }
            if (value > 35)
            {
                lblFS.ForeColor = System.Drawing.Color.Green;
            }
        }
    }