devxlogo

Referencing Controls on a Form with a Variable

Referencing Controls on a Form with a Variable

Question:
How do I use a variable to reference a control on a form? For instance, if I have five controls on a form named Edit1 through Edit5, and I make a for loop the builds the string “Edit1”, how do I use that string to refernce the actual control and use the control’s methods?

Answer:
If you’re using VB6, you can use the CallByName function to invoke methods or retrieve properties from objects that you reference through a variable.

If you’re not using VB6, you’ll have to do a Select/Case statement that looks at the string and uses the appropriate variable. If all the controls are the same type, you can Set the control into a variable of type Control or type TextBox, for instance. That will give you access to the properties/methods and the Intellisense drop-downs will also work. However, you will still have to look at the name of the string to figure out which control to set to the object variable.

devx-admin

Share the Post: