VB.NET通过控制面板中的控件跳过控件 [英] VB.NET Loop through controls in a panel skips controls
问题描述
Panel
移动到另一个VB.NET中,这似乎很简单: Public Sub Move(ByRef OldPanel As System.Windows.Forms.Panel)
Dim panelControl As System.Windows.Forms.Control
For Each panelControl在OldPanel.Controls
MessageBox.Show(panelControl.Name)'调试
OldPanel.Controls.Remove(panelControl)'相当肯定这条线没有区别
NewPanel.Controls.Add(panelControl )
下一个
结束小组
问题是,控制。其他面板完全没有被循环拾取,并保持绑定到 OldPanel
。我已经验证了这些控件是 OldPanel
中的一部分(不仅仅是可视化地浮动在上面)。
例如,如果面板上有6个控件, MessageBox.Show(panelControl.Name)
只反馈3个控件,只有3个控件移动。这是...令人困惑。
我在表单类 _Load
事件本身内写了一个类似的调试循环,正确地拿起面板上的所有6个控件:
pre $ Dim panelControl As System.Windows.Forms.Control
For Each panelControl In Me.Panel1.Controls
MessageBox.Show(panelControl.name)
Next
任何想法?
你正在改变集合,那就是在惹麻烦:一旦foreach开始并获得枚举值,枚举值就像开始时一样被绑定到集合上。
解决这个问题的一种方法是首先循环并收集要删除的控件列表。
然后循环列表并删除这些控件。<另一种方法是使用
作为
,它不会创建一个枚举器。 请注意,您的代码不会如果控件嵌套在另一个控件中,则工作。
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?
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.
这篇关于VB.NET通过控制面板中的控件跳过控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!