Nullify
Nullify

Reputation: 80

How do I change Color of Label by getting the Color from another Label?

I am trying to do something similar to the one in the example but changing the colour of the text/label.

Example:

Label1.Text = Label2.Text;
Label2.Text = Label3.Text;
Label3.Text = Label4.Text;
//so and and so forth

I am looking for a very simple solution like the one shown in the example but with colors. I am using Windows Form App with .Net Framework 4.7.2, I am using C# 9.0.

I have tried using .ForceColor as a way to change the color but as you can see, i am trying to accomplish a similar thing as the one in the example.

Upvotes: 0

Views: 366

Answers (1)

Muaath
Muaath

Reputation: 623

At first, I suggest put labels in a container, And don't put anything except labels. Then:

  1. Do for loop, and length = ContainerPanel.Controls.Count - 1, with condition i = ContainerPanel.Controls.Count
  2. Cast Control[i] to labelFirst
  3. Cast Control[i + 1] to labelSecond
  4. labelFirst.ForeColor = labelSecond.ForeColor

In this example, Container is: ContainerPanel

for (int i = 0; i < ContainerPanel.Controls.Count - 1; i++)
{
    // This is a simple way without variables
    (Label(ContainerPanel.Controls[i])).ForeColor = (Label(ContainerPanel.Controls[i + 1]));
}

Note: last Label You should change its ForeColor, Or it will not be changed.

Q&A

Q: Why length = ContainerPanel.Controls.Count - 1??

A: Because we should get Cast Control[i + 1] to labelSecond, And we can't, except if the length is less than controls count by one

Upvotes: 1

Related Questions