Reference an object w/ variables?

adude

Newcomer
Joined
Aug 19, 2003
Messages
22
Hi, i was wondering if there was anyway to reference an object (like a textbox called "txtName1", for example) with variable strings set to "txt" and "Name" and an integer that loops through numbers. I would like to be able to access its properties (Text, Enabled, etc.) dynamically.

I just started using VisualBasic, so I don't even have a guess at how to do this. I do know that in Macromedia Flash ActionScript, it's done by putting [], like this: _root[var1 + var2 + var3].symbol, etc.

I'm using VisualBasic .NET 2003.

Thanks.
 
The easiest way to do this would probably be like this:
Visual Basic:
Dim txt As New TextBox()
Dim tbReference As TextBox

For Each txt In Me.Controls
  If txt.Name = "txtName1" Then
    tbReference = txt
  End If
Next

'At this point in your code, [b]tbReference[/b] will reference the control you want.
'Just use it like you would a normal control.
 
That will work because all controls have the Name property, but if you will ever want to search by a property that is not accessile to all controls you will have to do it a slightly different:
Visual Basic:
Dim ctrl As Control
For Each ctrl In Me.Controls
     If TypeOf ctrl Is TextBox Then
          DirectCast(ctrl, TextBox).SelectionStart = 1
     End If
Next
This is just an example, if you didnt do this your would get an error about a cast being not valid if a control that was being checked didnt have this property. You have to check what type the control is, and then if you get what you want, cast the control variable used to iterate to the wanted type.

:)
 
Actually in my example, the enumerator control is a TextBox, so it doesn't matter what I search on, because it will only look through the TextBoxes. As long as the property I check belongs to TextBox, it's fine.
 
Looks like you're correct... I guess I was forgetting that Buttons have 'Text' properties too (not 'Caption' a la VB6).
 
Back
Top