VB.NET Loop through controls in a panel skips controls

后端 未结 2 558
轻奢々
轻奢々 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 03:05

    A common solution to this type of problem is to loop backwards over the collection. Then when you remove items it doesn't affect the index of the items you haven't seen yet:

    Public Class Form1
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            MoveControls(Panel1, Panel2)
        End Sub
    
        Public Sub MoveControls(ByVal OldPanel As Panel, ByVal NewPanel As Panel)
            Dim ctlCount As Integer = OldPanel.Controls.Count - 1
            For i As Integer = ctlCount To 0 Step -1
                NewPanel.Controls.Add(OldPanel.Controls(i))
            Next
        End Sub
    
    End Class
    

提交回复
热议问题