adude Posted August 19, 2003 Posted August 19, 2003 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. Quote
*Experts* Volte Posted August 19, 2003 *Experts* Posted August 19, 2003 The easiest way to do this would probably be like this: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. Quote
*Experts* mutant Posted August 19, 2003 *Experts* Posted August 19, 2003 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: 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. :) Quote
*Experts* Volte Posted August 19, 2003 *Experts* Posted August 19, 2003 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. Quote
*Experts* mutant Posted August 19, 2003 *Experts* Posted August 19, 2003 It will raise an error if a property is not accessible to a Control class, at least it raises one for me :) Quote
*Experts* Volte Posted August 19, 2003 *Experts* Posted August 19, 2003 Looks like you're correct... I guess I was forgetting that Buttons have 'Text' properties too (not 'Caption' a la VB6). Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.