How to find Label Controls inside a Form and its nested Panels?

前端 未结 2 1543
闹比i
闹比i 2020-12-07 04:39

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

相关标签:
2条回答
  • 2020-12-07 04:59

    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
    
    0 讨论(0)
  • 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.

    Get All Descendant Controls (children, children of children, ...)

    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
    
    0 讨论(0)
提交回复
热议问题