Search code examples
vb.netpanel

Cloning a panel inside a FlowPanel


I'm trying to clone multiple times a panel inside a FlowPanel... But it only clone once.

Dim NewFormConta1 As New Panel
NewFormConta1 = Panel1
PanelLateral.Controls.Add(NewFormConta1)

Dim NewFormConta2 As New Panel
NewFormConta2 = Panel1
PanelLateral.Controls.Add(NewFormConta2)

Dim NewFormConta3 As New Panel
NewFormConta3 = Panel1
PanelLateral.Controls.Add(NewFormConta3)

Result:

enter image description here

What I need:

enter image description here


Solution

  • Because these assignments are reference assignments

    NewFormConta1 = Panel1
    NewFormConta2 = Panel1
    NewFormConta3 = Panel1
    

    so your "new" panels all reference the same one panel. You only have one panel but 4 references to it.

    ' NewFormConta1 is a new panel
    Dim NewFormConta1 As New Panel
    
    ' NewFormConta1 points to Panel1 so the new panel from the first line
    ' is not referenced anymore and will be garbage collected
    NewFormConta1 = Panel1
    
    ' Panel1 is really added
    PanelLateral.Controls.Add(NewFormConta1)
    

    How do you populate Panel1? You could populate each NewFormConta the same way.

    Or another idea would be to make a User Control which has in it a Panel and the labels. You can modify the label properties with Public Properties in the User Control. Then just do this

    Dim NewFormConta1 As New UserControl1
    PanelLateral.Controls.Add(NewFormConta1)