VB.NET Loop through controls in a panel skips controls

后端 未结 2 563
轻奢々
轻奢々 2020-12-22 02:13

Written a quick subroutine in a class to move controls from one Panel to another in VB.NET, which seemed simple enough:

Public Sub Move(ByRef Ol         


        
2条回答
  •  再見小時候
    2020-12-22 02:55

    You are changing the collection while using for each to loop through it; that is asking for trouble: once the foreach is started and acquired the enumerator the enumerator is tied to the collection as it was at the start.

    One way to solve this is by first looping and collecting a list of controls to be deleted.

    Then loop the list and remove these controls.

    Another way is to use for which doesn't create an enumerator.

    Note that your code will not work if a control is nested within another control.

提交回复
热议问题