VB.NET中的控件数组 [英] Control array in VB.NET
问题描述
如何为 VB.NET 中的按钮制作控件数组?就像在 Visual Basic 6.0 中一样...
How do I make a control array for buttons in VB.NET? Like in Visual Basic 6.0...
有没有可能像下面这样的语法?
Is it possible that the syntax can be like the following?
dim a as button
for each a as button in myForm
a.text = "hello"
next
推荐答案
.NET 中的控件只是普通对象,因此您可以自由地将它们放入普通数组或列表中.不再需要特殊的 VB6 控件数组构造.
Controls in .NET are just normal objects so you can freely put them into normal arrays or lists. The special VB6 construct of control arrays is no longer necessary.
所以你可以说,
Dim buttons As Button() = { Button1, Button2, … }
For Each button As Button In Buttons
button.Text = "foo"
End For
或者,您可以直接迭代容器内的控件(例如表单):
Alternatively, you can directly iterate over the controls inside a container (e.g. a form):
For Each c As Control In MyForm.Controls
Dim btt As Button = TryCast(c, Button)
If btt IsNot Nothing Then ' We got a button!
btt.Text = "foo"
End If
End For
请注意,这仅适用于直接在表单上的控件;嵌套在容器中的控件不会以这种方式迭代;但是,您可以使用递归函数遍历所有控件.
Notice that this only works for controls that are directly on the form; controls nested into containers will not be iterated this way; you can however use a recursive function to iterate over all controls.
这篇关于VB.NET中的控件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!