I was just wondering if there is and alternative for control arrays in .net as these were quite handy in vb6?
Printable View
I was just wondering if there is and alternative for control arrays in .net as these were quite handy in vb6?
You can create your own pseudo control arrays in .Net... the only thing you can't do is create multiple controls with the same name.
For example you can dimension an array of controls like this :
and add to it like this :Code:Dim MyControls(20) as control
Code:For X as integer = 0 to 20
Dim MyNewControl As New Label
MyNewControl.Text = "Label " & x.ToString
MyControls(MyControls.count) = MyNewControl
Next X
Ok cool thanks I shall give that a try.
I have another question, maybe you can help. If I was using the following code:
Is there a way of controlling the order of controls it loops through? Does it go based on which ones are created first?Code:For Each Cntrl as Control in me.controls
'Some Code'
Next Cntrl
Im basically helping someone with a game but the way I have gone about it is changing the text of labels one by one. In the game there is 160 labels so not very efficient to change these one by one.
It most likely goes through the collection based on the order the controls was added to the collection.
Altough this question really should be in a separate thread, could I ask in what way you would like to control the iteration?
As Atheist says, this should probably be a new thread, but I'll just chuck in a thought : If you are using VB.Net 2008 you can probably use LINQ to get all the controls ordered by the value of a specific property.Quote:
Is there a way of controlling the order of controls it loops through?
Well basically I'm adding data from a text file into the labels text property so i basically need to iterate through the labels in some sort of order such as Label1, Label2, Label3 so I can make sure the right data is going in to each label.
You could add an identifier into the tag property of each control in the collection (either at design time or at run time if you are creating controls on the fly).
Then you could look up the appropriate value for the control using that identifier.
The order of controls is meaningless for a FOR EACH... NEXT loop. The iterator usually picks them up in order, but this is not guaranteed.
If you want to get controls in fixed order, you should use a loop variable.
vb.net Code:
For i as Integer = 0 To Me.Controls.Count -1 MsgBox(Me.Controls(i).Name) Next
Ok problem solved that works fine. I was originally trying to identify the control by checking if the name contained a number but then when it came to checking say Label11 and the value of I in my integer loop was 1 this would get the wrong data.
Thanks for the help