I need to change the background color of all the Labels inside a Form and nested Panels.
I tried this code but it only changes the color of the Labels that are i
You could setup a simple recursive method that parses all Controls in a Form.
When a Control in the collection is of type Label
, set the BackColor
property.
When the Control contains other Controls, parse its Controls
collection to see whether it contains some Labels; when one is found, set its BackColor
.
Call the method:
SetLabelsColor(Me, Color.AliceBlue)
Recursive method:
Private Sub SetLabelsColor(parent As Control, color As Color)
If (parent Is Nothing) OrElse (Not parent.HasChildren) Then Return
For Each ctl As Control In parent.Controls.OfType(Of Control)
If TypeOf ctl Is Label Then
ctl.BackColor = color
Else
If ctl.HasChildren Then
SetLabelsColor(ctl, color)
End If
End If
Next
End Sub
If you want to modify the Labels that are inside Panels and not other containers, you could modify the condition that triggers the recursion:
If (TypeOf ctl Is Panel) AndAlso (ctl.HasChildren) Then
SetLabelsColor(ctl, color)
End If
The answer which is shared by Jimi is quite good for the question. But I'd like to share a more general answer which shows how you can use Extension Methods, Iterator Functions, LINQ and Enumerable extension methods.
You can create an extension method to list all descendants of a control. When writing this method, you can easily take advantage of Iterator functions and Recursive functions to return an IEnumerable<Control>
:
Imports System.Runtime.CompilerServices
Module ControlExtensions
<Extension()>
Public Iterator Function DescendantControls(c As Control) As IEnumerable(Of Control)
For Each c1 As Control In c.Controls
Yield c1
For Each c2 As Control In c1.DescendantControls()
Yield c2
Next
Next
End Function
End Module
Then you can use the extension method to get all descendants and use OfType
to filter to specific type of control:
For Each c In Me.DescendantControls().OfType(Of Label)
c.BackColor = Color.AliceBlue
Next