Home > front end >  Im trying to change buttons colors on VB.NET
Im trying to change buttons colors on VB.NET

Time:12-25

Thats not my code

Private Sub SetAllLabelsForeColor(ByVal parent As Control)

        For Each c As Control In parent.Controls
            If TypeOf (c) Is Button And c.BackColor = Color.Red Then
                c.FlatAppearance.MouseOverBackColor = Color.White 'I AM STUCK HERE
            Else
                If c.HasChildren Then
                    SetAllLabelsForeColor(c)
                    Dim b = DirectCast(c, Button)
                    b.FlatAppearance.MouseOverBackColor = Color.White 'I AM STUCK HERE
                End If
            End If
        Next

    End Sub

CodePudding user response:

are you working with WinForms or WPF?

If you are on WPF then buttons have properties that are defined enter image description here

Extension method

Public Module ControlExtensions
    <Runtime.CompilerServices.Extension>
    Public Iterator Function Descendants(Of T As Class)(control As Control) As IEnumerable(Of T)
        For Each child As Control In control.Controls
            Dim thisControl As T = TryCast(child, T)
            If thisControl IsNot Nothing Then
                Yield thisControl
            End If

            If child.HasChildren Then
                For Each descendant As T In child.Descendants(Of T)()
                    Yield descendant
                Next
            End If
        Next
    End Function

End Module

Form code

Public Class Form1
    Private Sub ChangePropertiesButton_Click(sender As Object, e As EventArgs) _
        Handles ChangePropertiesButton.Click

        Dim Panel1Buttons = Panel1.Descendants(Of Button).Where(
            Function(b) b.FlatStyle = FlatStyle.Flat AndAlso b.BackColor = Color.Red).ToList()

        For Each panel1Button As Button In Panel1Buttons
            panel1Button.FlatAppearance.MouseOverBackColor = Color.White
        Next

        ListBox1.DataSource = Panel1Buttons.Select(Function(button) button.Name).ToList()
    End Sub
End Class

Going back to your code, SetAllLabelsForeColor is a bad name for what the method does, even if you copy-n-pasted from somewhere always provide meaningful names to methods and controls.

  • Related