reference a control by string.

N

nate axtell

I'm looking for a way to refernce a control by a string that represents the
name of the control. I dynamically create some textboxes, labels, and
comboboxes each name by a loop iteration index. (E.G.: "combo" & i) These
are added to the controls of a panel. How can I at a later time reference
these items in a panel by using "combo0", "combo1", etc... using a string
variable? An example would be the removal of one of the items from the
control. So far all I can find is:
Me.myPanel.Controls.Remove(myControl)
or
Me.myPanel..Controls.IndexOf(myControl)

Any suggestions?
thanks
nate
 
G

Guest

Create a Hashtable

When you create the control, add it to the hashtable, using the name you
create as key.

When you need access to the control, you should declare a variable as the
control type and use directcast to cast it correctly.

When you create controls:
dim HT as new Hashtable
(in loop)
Dim Txt as new Textbox
....
HT.add("T1", Txt)
Dim Cbo ...
HT.add("C1", Cbo)

When you need to use a control:

Select Case HT("T1").gettype.name.tolower
Case "textbox"
Dim Txt as Textbox = Directcast(HT("T1"), Textbox)
Case "combobox"
....
End Select

You can loop through a Hashtable using For Each Loop.
 
N

nate axtell

I was also hoping not to have to loop through all of the controls, so I
think I will use the HashTable or Array method that it suggests.
Thanks for the link.

Does anyone have another method?
nate
 
N

nate axtell

I went with the Hashtable method, thanks.
nate

Charlie said:
Create a Hashtable

When you create the control, add it to the hashtable, using the name you
create as key.

When you need access to the control, you should declare a variable as the
control type and use directcast to cast it correctly.

When you create controls:
dim HT as new Hashtable
(in loop)
Dim Txt as new Textbox
...
HT.add("T1", Txt)
Dim Cbo ...
HT.add("C1", Cbo)

When you need to use a control:

Select Case HT("T1").gettype.name.tolower
Case "textbox"
Dim Txt as Textbox = Directcast(HT("T1"), Textbox)
Case "combobox"
...
End Select

You can loop through a Hashtable using For Each Loop.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top