首页 > 解决方案 > 对于每个控件

问题描述

我在使用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.netwinformsbutton

解决方案


尝试:

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

... 或者

For Each c In Controls.OfType(Of Button).
    Where(Function(x) x.Name.StartsWith("Test")).ToList
    Controls.Remove(c) 'Or c.Dispose()
Next

... 或者

For Each c In Controls.OfType(Of Button).
    Where(Function(x) x.Name.StartsWith("Test")).Reverse()
    Controls.Remove(c) 'Or c.Dispose()
Next

...在循环它的集合时删除一个对象。


推荐阅读