Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

Control array in VB.NET

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

So you can for example say,

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...