views:

37

answers:

1

I have several sets of similar objects (labels, progress bars) on a form in Visual Basic 2010 on Windows. In my code, I have collections that contain data, which needs to be pushed into the value/text property of each.

I would like to get a solution similar to PHP in that I can assign values somewhat like:

For ID as Integer from 0 to count(collectionExample) lblExample{ID}.Text=collectionExample(variableID)

...and as such to loop through so each of the different lblExample's were updated to their corresponding value.

The issue I have come to is that I cannot seem to reference an object on the form using a variable. I have also tried using something like

CallByName("lblExample" + variableID, "Text", CallType.Set, exampleCollection(variableID))... however I still can't combine the string and variable to reference the object.

Any solutions on referring to objects in VB2010 by combining a string prefix and a variable string identifier, similar to PHP's $variable{$variable} approach?

Edit: Windows Platform

A: 

You could add each of the controls to a dictionary, using a string as the key.

Then you can access the controls using the string.

Here is a simple example, replace the for loop with you foreach loop...

There may be a cleaner way to associate you data with controls, like putting the controls in a collection indexed by an integer (ID in your example), but you asked for a string!

Public Class Form1

Dim ctrlDict As New Dictionary(Of String, Control)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    ctrlDict.Add("label1", Label1)
    ctrlDict.Add("label2", Label2)

    For i As Integer = 1 To 2
        ctrlDict("label" & i).Text = "Test" & i
    Next
End Sub

End Class
B Pete