I’m a bit confused here. I’m copying all the controls from one form to a panel on the main form and for some reason only about half of them copy.
Private Sub switchComponent()
Dim selection As String = TreeView1.SelectedNode.Text
Panel1.Controls.Clear()
Dim query = From cont In serverDic(selection).Controls
Select cont
For Each copier As Control In query
Panel1.Controls.Add(copier)
Next
End Sub
serverDic is defined as:
Dim serverDic As New Dictionary(Of String, frmServer)
When stepping through the code, serverDic(selection).Controls has 12 elements, but only 6 of them get copied. Next time this gets called, only 3 get copied. Does Panel1.Controls.clear() somehow kill the references?
EDIT: Just to show that there are infact 12 elements in the collection:

The problem here is that you are iterating over a collection that you are changing. When you add a
Controlto an container it is implicitly removed from it’s previous parent and hencequery. This is why you see exactly half of the items get removed.With most collections this would be more apparent because they would throw if modified during an enumeration. The primary source of
queryhere though isControlCollectionwhich does allow for modifications while enumerating.To fix this problem just add the following line before the
For Eachloop.