Home > Software design >  How to make loop for panels background color from a module VB.NET
How to make loop for panels background color from a module VB.NET

Time:12-05

I have this code in a module in VB.NET so pp1 is a panel

    Public Sub changecolor(ByRef curruntpanel As Panel)
        On Error Resume Next
        Main_Form.PP1.BackColor = SystemColors.Control
        Main_Form.PP2.BackColor = SystemColors.Control
        Main_Form.PP3.BackColor = SystemColors.Control
        Main_Form.PP4.BackColor = SystemColors.Control
        Main_Form.PP5.BackColor = SystemColors.Control
        Main_Form.PP6.BackColor = SystemColors.Control
        Main_Form.PP7.BackColor = SystemColors.Control
        Main_Form.PP8.BackColor = SystemColors.Control
        Main_Form.PP9.BackColor = SystemColors.Control
        Main_Form.PP10.BackColor = SystemColors.Contrl

        curruntpanel.BackColor = Color.White
    End Sub

and I want to replace it with loop code so I tried the next code but it's not working with me

        Dim i As Integer
        For i = 1 To 10
            Main_Form.Controls("pp" & i).BackColor = SystemColors.Control
        Next

        curruntpanel.BackColor = Color.White

this code in a module too So can anyone give me the right code for loop?

I want help to turn into some lines to loop code

CodePudding user response:

Try changing the Name of the control in the loop from, pp to PP. Here's an example:

Public Sub changecolor(ByRef curruntpanel As Panel)
    Dim i As Integer

    For i = 1 To 10
        Main_Form.Controls("PP" & i).BackColor = SystemColors.Control
    Next
    curruntpanel.BackColor = Color.White
End Sub

CodePudding user response:

Pass the instance of the form where your panels are contained.

Public Sub changecolor(ByVal formInstance As Form, ByVal curruntpanel As Panel)
    For Each ctrl As Control In formInstance.Controls
       If TypeOf ctrl Is Panel Then
          If CType(ctrl,Panel).Name.StartsWith("PP") Then
             CType(ctrl,Panel).BackColor = SystemColors.Control
          End If
       End If
    Next
    curruntpanel.BackColor = Color.White
End Sub
  • Related