adding controls at runtime

T

Tym

I was looking for a way to add a control array at runtime - but it
doesn't look like vb.net has that ability any more...

Was looking at controls one at a time thus:

Dim Label1 As New Label
Label1.Text = "label 1"
Label1.Location = New Point(20, 25)
Me.Controls.Add(Label1)

Is there any easy way of doing domething like.....

For I = 1 to 100
Dim Label(I) As New Label
Label(I)1.Text = "label " & I
Labe(i)1.Location = New Point(20 * I, 25)
Me.Controls.Add(Label(I))
Next I

of perhaps dynamically naming the variable in the dim statment


for I = 1 to 100
sLabel(i) = "LABLE_NO_" & I
next I
Dim sLABEL(I).text As New Label
if you know that I mean...
 
A

Altman

You are somewhat close. Declare an array of labels first
dim myLabel(100) as label

Then do the for loop and create new instances of the label class and store
them in the array

For I = 1 to 100
myLabel(I) = new label
myLabel(I).Text = "Whatever"
Me.Controls.Add(Label(I))
Next I
 
G

Guest

There is no inherent index property for controls. Here is a piece of code
that brings the old VB6 way of doing things into an object oriented
environment: This would go into the Load event of the form.

*****start code******

Dim i As Int32
Dim LBL As Label
Dim AL_Labels As New ArrayList()
For i = 0 To 9
LBL = New Label()
With LBL
.Location = New Point(100, i * 24)
.Size = New Size(100, 20)
.Name = "LBL_" & i.ToString
.Text = "Label " & i.ToString
End With
Me.Controls.Add(LBL)
AL_Labels.Add(LBL)
Next

LBL = DirectCast(AL_Labels(7), Label)
MessageBox.Show(LBL.Text, LBL.Name)

******end of code*******

You would probably put AL_Labels outside the Load event and give it the
scope you need.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top