对于每个控件

问题描述 投票:0回答:1

我在使用For Each循环时遇到问题:

如果运行此循环,我可以看到所有(假设是)100个控件。

For each Btn as Control in Controls
   If TypeOf Btn Is Button then
      If instr(1,Btn.Name,"Test",0) Then Debug.Print(Btn.name)
   End If   
Next

但是,如果我需要删除它们,则循环似乎使遍历控件的循环变得混乱,并且跳过了一些...

For each Btn as Control in Controls
   If TypeOf Btn Is Button then
      If instr(1,Btn.Name,"Test",0) Then Controls.Remove(Btn)
   End If   
Next

每次删除控件后,我都试图重新启动循环,但是解决方案却不是那么...优雅。

反正有解决此问题的方法吗?

vb.net winforms button
1个回答
1
投票

尝试一下:

    For i As Integer = Controls.Count - 1 To 0 Step -1
        If TypeOf Controls(i) Is Button AndAlso Controls(i).Name.StartsWith("Test") Then
            Controls.RemoveAt(i) ' or Controls(i).Dispose()
        End If
    Next
© www.soinside.com 2019 - 2024. All rights reserved.