-1

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...

arc95
  • 97
  • 1
  • 8

2 Answers2

1

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.

dotNET
  • 33,414
  • 24
  • 162
  • 251
  • Yes! that solved my problem!! after 3 days!! i add back in the same way the controls to form1! I've dismissed that... i'm just supossing just the forms works as containers... very basic! thanks a lot! – arc95 Aug 12 '17 at 06:47
0

As stated by dotNET, You need to maintain a reference to the object.

Example:--

//To store existing picture boxes- 

Dim MyObjects as new list(of Picturebox)

Private sub RemoveObJect(Obj as pictureBox)
   //remove the object from flowlayoutpanel
   FlowLayoutPanel1.Controls.remove(Obj)
   //Add the object to a collection - I would wrap the object into a custom
   //Class to hold more information about it 
   MyObjects.add(Obj)
End Sub

Private sub RestoreObJect(Obj as pictureBox)
   //reverse the remove procedure
   FlowLayoutPanel1.Controls.add(Obj) //or add to a specific index
   MyObjects.remove(Obj)
End Sub






Private Sub RemoveObject(Obj as button) ...
ThatGuy
  • 228
  • 1
  • 12