【问题标题】:For Each Control对于每个控件
【发布时间】:2019-10-03 08:29:11
【问题描述】:

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

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

有没有办法解决这个问题?

【问题讨论】:

  • For each Btn as Control in Controls.ToList()
  • 枚举时不能从列表中删除项目。您需要创建另一个列表并在从 origjanl 列表中删除时枚举该列表,如@GSerg 演示的那样,或者使用For 循环并向后循环,以便删除项目不会影响其余项目的索引。
  • 另外,如果您只想要Buttons,请执行以下操作:Controls.OfType(Of Button)().ToList()。如果您只想要名称以“Test”开头的Buttons,请执行以下操作:Controls.OfType(Of Button)().Where(Function(b) b.Name.StartsWith("Test")).ToList()
  • 最后,除非您打算再次使用它们,否则您应该处置那些Buttons。释放控件会自动将其从其父级中移除,因此您只需调用 Dispose

标签: vb.net winforms button


【解决方案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

... 或

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

...在循环它是集合时移除一个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 2020-09-11
    • 2011-01-05
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多