VB.NET 循环通过面板中的控件跳过控件 [英] VB.NET Loop through controls in a panel skips controls

查看:25
本文介绍了VB.NET 循环通过面板中的控件跳过控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个类中编写了一个快速子例程,以在 VB.NET 中将控件从一个 Panel 移动到另一个,这看起来很简单:

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

问题是,它只移动了大约一半的控件.其他面板根本不会被循环拾取,并且仍然绑定到 OldPanel.我已经验证这些控件绝对是 OldPanel 的一部分(而不仅仅是在视觉上浮动在它上面).

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).

例如面板上有6个控件,MessageBox.Show(panelControl.Name)只反馈其中的3个,并且只有这3个控件移动.这真是……莫名其妙.

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.

我在表单类 _Load 事件本身中编写了一个类似的调试循环,这正确地选择了面板上的所有 6 个控件:

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

有什么想法吗?

推荐答案

您正在更改集合,同时使用 for each 循环遍历它;这是在自找麻烦:一旦 foreach 启动并获得枚举器,枚举器就会像开始时一样绑定到集合.

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.

另一种方法是使用 for ,它不会创建枚举器.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆