Search code examples
vb.netfor-looppictureboxflowlayoutpanel

reuse controls at flowlayoutpanel


I have 3 buttons: 1ºbtn adds 3 pictureboxes into flowlayoutpanel. 2ºbtn try to remove the controls from flowpanel 3ºbtn add again only 2 pictureboxes into flowlayoupanel

the code i use (loop) to add pictureboxes named as picturebox1,picturebox2 into flowpanel is this:

For i As Integer = 1 To 3
        If Me.Controls.ContainsKey("PictureBox" & i) Then
            Me.Controls("PictureBox" & i).Visible = True
            Me.Controls("PictureBox" & i).Margin = New Padding(0)
            Dim px As PictureBox = CType(Me.Controls("PictureBox" & i), PictureBox)
            FlowLayoutPanel1.Controls.Add(px)
End If
next

the remove codes i've tried are these:

FlowLayoutPanel1.Controls.clear()

also i've tried:

While
(FlowLayoutPanel1.Controls.Count > )FlowLayoutPanel1.Controls.RemoveAt(0)
End While 

also:

For i As Integer = 1 to 3
If Me.Controls.ContainsKey("PictureBox" & i) Then
Me.Controls("PictureBox" & i).remove()
Me.Controls("PictureBox" & i).Visible = False

i've also tried:

For i As Integer = 1 to 3
If Me.Controls.ContainsKey("PictureBox" & i) Then
Me.Controls("PictureBox" & i).Dispose() 

All that codes to remove works fine but then i cannot add again the same pictureboxes into any flowpanel again...


Solution

  • When you remove a control from a container, you need to add it back to another one before you lose its reference. Remember that any object that is not being referenced by anything will eventually be collected (deleted) by the GC. So when you call Remove() or Clear(), immediately add it back to the main Form or a local Form-level collection so that it keeps in the memory.