Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

winforms - VB.NET Loop through controls in a panel skips controls

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 OldPanel As System.Windows.Forms.Panel)
    Dim panelControl As System.Windows.Forms.Control
    For Each panelControl In OldPanel.Controls
        MessageBox.Show(panelControl.Name) 'Debugging
        OldPanel.Controls.Remove(panelControl) 'Fairly certain this line makes no difference
        NewPanel.Controls.Add(panelControl)
    Next
End Sub

The problem is, it only moves about half the controls. The other panels aren't picked up by the loop at all and remain bound to OldPanel. I have verified that the controls are definitely part of the OldPanel (and not just visually floated above it).

For example, if there are 6 controls on the panel, MessageBox.Show(panelControl.Name) only feeds back 3 of them, and only those 3 controls move. This is... baffling.

I wrote a similar debugging loop inside the form class _Load event itself and this correctly picks up all 6 controls on the panel:

Dim panelControl As System.Windows.Forms.Control
For Each panelControl In Me.Panel1.Controls
    MessageBox.Show(panelControl.name)
Next

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...