none
Giving Random Colors to different panels RRS feed

  • Question

  • Hi guys,

    Im trying to randomly give every panel on my form a color.

    This is my code so far, it gives a random color, but all panels does have the same color.

    Private Function RandomizeColor() As Color
            Dim rand As New Random
            RandomizeColor = Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, _
                256))
    End Function
    
    Private Sub Dashboard_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each CPanel As Object In Me.Controls
       If TypeOf CPanel Is Panel Then
           Cpanel.BackColor = RandomizeColor()
       end if
    next
    end sub
    
    

    I hope someone could help me out with this :)

    Regards,

    Kevin 

    Tuesday, July 10, 2018 9:23 PM

Answers

  • Hi

    You were very very close. All that was needed was tomove the rand declaration out of the function. Like this:

    Option Strict On
    Option Explicit On
    Public Class Form1
      Dim rand As New Random
      Private Function RandomizeColor() As Color
        RandomizeColor = Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0,
            256))
      End Function
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For Each CPanel As Control In Me.Controls
          If TypeOf CPanel Is Panel Then
            CPanel.BackColor = RandomizeColor()
          End If
        Next
      End Sub
    
    End Class


    Regards Les, Livingston, Scotland

    Tuesday, July 10, 2018 9:40 PM

All replies

  • Hi

    You were very very close. All that was needed was tomove the rand declaration out of the function. Like this:

    Option Strict On
    Option Explicit On
    Public Class Form1
      Dim rand As New Random
      Private Function RandomizeColor() As Color
        RandomizeColor = Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0,
            256))
      End Function
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For Each CPanel As Control In Me.Controls
          If TypeOf CPanel Is Panel Then
            CPanel.BackColor = RandomizeColor()
          End If
        Next
      End Sub
    
    End Class


    Regards Les, Livingston, Scotland

    Tuesday, July 10, 2018 9:40 PM
  • Awesome Les! Thank you verry much :)


    Tuesday, July 10, 2018 11:43 PM