删除 GroupBox 内的控件
我创建了一个组框,然后在运行时用按钮填充它。我还创建了一个按钮(例如 Button1)来循环组合框并删除这些按钮。这是我的代码 for Button1:
Public Sub removeControls()
For Each ctrl As Control In GroupBox1.Controls
GroupBox1.Controls.Remove(ctrl)
ctrl.Dispose()
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
removeControls()
End Sub
执行时,它仅删除 GroupBox1 内的部分控件,而不是全部。您能解释一下我的代码中缺少什么才能使其正常工作吗?谢谢。
I created a groupbox and then populate it with buttons during runtime. I also created a button, say Button1 to loop through the groupbox and delete those buttons. Here's my code
for Button1:
Public Sub removeControls()
For Each ctrl As Control In GroupBox1.Controls
GroupBox1.Controls.Remove(ctrl)
ctrl.Dispose()
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
removeControls()
End Sub
When executed, it only removes some of the controls inside the GroupBox1, not all. Can you explain what is missing in my code to make it work? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您删除
For Each
循环中的控件时,您实际上是在修改您尝试循环遍历的集合。当您删除集合中的第一项时,第二项向上移动成为第一项。但现在,当您到达循环的第二个索引时,第三 项就位于其位置。您实际上跳过了删除第二项,而只删除了第一项和第三项。依此类推,贯穿整个循环。相反,您需要按相反顺序循环遍历控件,并删除每个索引处的项目。从末尾开始删除项目,不会影响顺序或物品的位置。
因此,只需将您的方法更改为以下内容:
When you delete controls in a
For Each
loop, you're actually modifying the collection that you're trying to loop through. When you remove the first item in the collection, the second item moves up to become the first. But now, when you reach the second index of your loop, the third item is in its place. You've effectively skipped removing the second item, and only removed the first and third. And so on through the entire loop.Instead, you need to loop through the controls in reverse order and remove the item at each index. By starting to removing items from the end, you won't affect the order or position of the items.
So, just change your method to the following:
当您遍历集合时,您正在更改集合,但不应该这样做。
而是使用类似的东西
You are changing the collection as you are itterating through it, and that should not be done.
Rather use something like