Reference an object w/ variables?

adude

Member
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 dont even have a guess at how to do this. I do know that in Macromedia Flash ActionScript, its done by putting [], like this: _root[var1 + var2 + var3].symbol, etc.

Im using VisualBasic .NET 2003.

Thanks.
 
The easiest way to do this would probably be like this:
Code:
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:
Code:
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 doesnt matter what I search on, because it will only look through the TextBoxes. As long as the property I check belongs to TextBox, its fine.
 
Looks like youre correct... I guess I was forgetting that Buttons have Text properties too (not Caption a la VB6).
 
Back
Top