Changing Dynamic Controls at Runtime

jrunowski

Member
Joined
Aug 23, 2006
Messages
15
Programming Experience
Beginner
Hello,
I was wondering how to change the text of a label at runtime after it was created using the Controls.Add function. Since i am using dynamic values to create these controls i dont know the name of the control until after it has been created.

For Example: I Use this code to create the controls
VB.NET:
Public Sub Create_Machine_Totals ([SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] machine_name [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]String)
[/COLOR][/SIZE][COLOR=#0000ff]Dim[/COLOR] lblTotalCountPos [SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] Point(302, 55)
[/SIZE][SIZE=2][/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] TotalCount [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] System.Windows.Forms.Label[/SIZE]
[SIZE=2] 
TotalCount.Size = [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] System.Drawing.Size(50, 16)
TotalCount.Location = lblTotalPos
TotalCount.Name = [/SIZE][SIZE=2][COLOR=#800000]"lbl"[/COLOR][/SIZE][SIZE=2] + machine_name + [/SIZE][SIZE=2][COLOR=#800000]"total"
[/COLOR][/SIZE][SIZE=2][/SIZE][SIZE=2]TotalCount.Text = [/SIZE][SIZE=2][COLOR=#800000]"0"
[/COLOR][/SIZE][SIZE=2]TotalCount.ForeColor = Color.Black
lblTotalPos.Y += 38
 
me.Controls.Add(libtotal)
End Sub
[/SIZE]

There are about 25 labels that get created using the Create_Machine_Totals sub from an array list. Once the controls have been created i want to pediocally update the labels with their new totals. How can i do this?

I tried this, but i just get errors:
VB.NET:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
 
("lbl" + namesarray(x) + "total").text = "500"
 
End Sub

Any help with this would be great, thank you so much.
 
You have to give them distinct names, use a counter variable. Later search the Controls collection for a control by the name you need.
 
Loop it: For Each c As Control in yourcontainer.Controls .... Next.
 
Thanks JohnH i'll give that try, I was reading a lot of articles on this and it seems like control arrays in vb6 would have worked. I wonder why they removed them from .net?
 
Why is not Controls collection good enough? I think it is much better than "control arrays"
 
So far it just seems it would have been easier; granted i am an extreme newbie. I think i just need to read up more on Control Collections.
 
Back
Top