Home > Software design >  How do you set a dynamically created panel to false in VB.net?
How do you set a dynamically created panel to false in VB.net?

Time:01-08

I have on my screen design Panel1(left half), and panel2 through 10(right half), the panels on the right half are named based on data from a database.

I need to be able to click on a button in panel1 and when I do so, I need to set visibility to false for the current panel on the right half and set visibility to true that is referenced from the button click. I know that I can do the following but I think this is just way too much overhead and there has to be a better solution than this:

For Each control In Me.Controls.OfType(Of Panel)
     If control.visible = true Then
          control.visible = false        
          exit  
Next

Panel that the visibility that needs to be set to false was dynamically created so it can not just be accessed by just name, otherwise that would solve my issue easily.

I seen this bit of code elsewhere and it would make my life easier, however not sure how to implement it dynamically when the panels are created, since the name of the panels are unknown at creation.

This bit of code to be able to reference the panels directly.

Dim machinePanel As Panel = DirectCast(Me.Controls.Item("pnl" & strMTB & strMachineID), Panel)

CodePudding user response:

I'm not sure what you mean but "is referenced from the button click", so I'll assume that the text of the button refers to the panel name.

Create a method that handles the visibility

Private Sub SetPanelVisibility(button As Button)
    'panel that the button is in
    Dim leftPanel = CType(button.Parent, Panel)

    'get right panels and ignore left
    Dim rightpanels = Me.Controls.OfType(Of Panel).Where(Function(x) x.Name <> leftPanel.Name)

    'set visibility of each panel.
    For Each panel In rightpanels
        panel.Visible = panel.Name = button.Text
    Next
End Sub

To call the method just pass the button in on the click event. e.g.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    SetPanelVisibility(sender)
End Sub
  • Related