0

I'm writing a WinForms application. I have many labels which represent some status (Enabled/Disabled etc). I want each status to be different color (green, grey...). The only way I know to achive this is to check whether label.Text matches required status and then change its ForeColor. But this is a hard way, as I need to perform this check every time I set status label in my application.

I wonder if there is any way to do it "in one place?". For example writing a method that will check all labels for specific string and just call it from Form_Load()

lukiffer
  • 11,025
  • 8
  • 46
  • 70
artman
  • 632
  • 2
  • 7
  • 16

4 Answers4

3

You could create your own custom label class which inherits from the Label class. Something like this:

public class MyLabel : Label
{
    public MyLabel()
    {
        if(this.Text == "something")
        {
            this.ForeColor = Color.Green;
        }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        if(this.Text == "something")
        {
            this.ForeColor = Color.Green;
        }
    }
}

And so instead of using Label use MyLabel everywhere.

c0deNinja
  • 3,956
  • 1
  • 29
  • 45
1

Add all your labels to a List on Form_Load(), then you can do a .Where(l => l.Text == "String you are looking for"). Iterate through those to set the forecolor appropriately

Ryan Bennett
  • 3,404
  • 19
  • 32
0

Enumerate all labels on Form using Form Controls and it's child controls, for example use GetAll method from this SO answer :

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

And then set appropriate color, something like this :

var allLabels = GetAll(form, typeof(Label)); /// you can use this as first param if in form methods
foreach(Label oneLabel in allLabels)
{
  if (oneLabel.Text == "Something")
  {
    // set color or whatever
  }
}
Community
  • 1
  • 1
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
0

You can also take advantage of Tag property of label control. Set Tag to "Status" for all label controls you are using to display status and in Page_Load event, rotate a loop to set ForeColor.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For Each control In Me.Controls
        If (TypeOf (control) Is Label) Then
            Dim statusLabel As Label
            statusLabel = control
            If (statusLabel.Tag = "Status") Then
                statusLabel.ForeColor = Color.Red
            End If
        End If
    Next
End Sub
Firoz Ansari
  • 2,505
  • 1
  • 23
  • 36