vb.net - 对于每个控件
问题描述
我在使用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 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
...在循环它的集合时删除一个对象。
推荐阅读
- angular - 如何在不刷新的情况下更新角度页面?
- mysql - 计算子选择 SQL 的百分比
- algorithm - 在无向图中找到所有循环的任何有效算法?
- r - Rstudio 在控制台中呈现,但在 Markdown 中输出到 HTML 时出错
- r - dplyr::case_when 等效于一列一组
- c# - Unity 的 AnimationCurve 序列化/分配有什么不同,为什么我的示例会失败?
- mysql - MySQL 联合表 SUM 和额外子句
- python - 使用 python 和 selenium 在元素内部搜索另一个元素
- r - 减少 R 中的数据集 - 过滤和分组?
- javascript - 如何构建这个简单的正则表达式?