r/visualbasic • • Feb 23 '19

Interacting with programmatically created items

I am fooling around with creating thing dynamically in code(buttons, text boxes, simple thing). So far I understand the very basics of creating them. For example for a combobox I do:

Dim combobox As New ComboBox
            With combobox
                .Location = New Size(20 * i, 20 * i)
                .Name = "Combobox1"
                .Items.Add("one")
            End With
            Me.Controls.Add(combobox)

I put this on a button and it makes the combobox appears. My question is, after its been generated, how can I interact with it?

I have the .name property to label it as Combobox1, but when I try to add something outside of the With|EndWith box that refers to combobox1 I get an error that says it is undefined or unavailable due to protection level.

How can I interact with it once its been created, or is that not something thats done?

6 Upvotes

8 comments sorted by

View all comments

2

u/PostalElf VB.Net Intermediate Feb 23 '19

You'll need to maintain a reference to it, most likely in a form-level variable or collection. Alternatively, you'll have to trawl through Form.Controls and search for the item you want, most likely through its .name property.

2

u/Thunor_SixHammers Feb 23 '19

Interesting. So if I understand correctly I need to do first creat a collection of names I intend to use, then create the item and assign it a name from the aforementioned collection and I can refer to it.

2

u/PostalElf VB.Net Intermediate Feb 23 '19

That's an option, definitely. If that's what you want to do, I'll recommend using a Dictionary(Of String, Control) and then accessing the control through the control's name that is stored in the dictionary's keys.

1

u/Thunor_SixHammers Feb 23 '19

I've never used the dictionary in that way. I've done (key,value) where it's string and integer.

Could you give me an example of using control?

2

u/andrewsmd87 Web Specialist Feb 23 '19

You'd just define your dictionary as string, control instead of int, string

In this case your key is just a way to identify it and you "value" is actually a control object

1

u/PostalElf VB.Net Intermediate Feb 23 '19
Dim ControlDict as New Dictionary(Of String, Control)
Dim ComboBox as New Combobox
With ComboBox
  ...
  .Name = "NameBox"
End With
Me.Controls.Add(ComboBox)
ControlDict.Add("NameBox", ComboBox)