Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

c# - Is there a way to change the color of 'n' labels together with one command?

Is there a way to change the color of 10 labels together with one command?

For example, instead of:

Label1.ForeColor = Color.Black
Label2.ForeColor = Color.Black
Label3.ForeColor = Color.Black
Label4.ForeColor = Color.Black
Label5.ForeColor = Color.Black
Label6.ForeColor = Color.Black
Label7.ForeColor = Color.Black

I would like to use only one command to change the ForeColor. For example, instead of Label1 it would be LabelX.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can just loop through all the controls of type label. This should do the trick.

'For each control in the form
For Each ctrl As Control In Me.Controls
    'If its of type label
    If TypeOf ctrl Is Label Then
        'Change the color
        ctrl.ForeColor = Color.Black
    End If
Next

Edited like Vincent suggested so we don't need to declare ctr before.

As Bugs suggested here is an even shorter option:

For Each ctr In Me.Controls.OfType(Of Label)
    ctr.ForeColor = Color.Black
Next

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...