How to deal with controls created programmatically

S

Siv

Hi,
I have an application that reads information from a database and depending
on that information creates controls on a form. Depending on where the user
is at in a process there may be one item or many items. I create check
boxes, one for each entry I get back from the database.

The code therefore does stuff like this:

cb = New CheckBox
tpMain.Controls.Add(cb)

x = 50 : y += 25
cb.Left = x
cb.Top = y
cb.Text = CStr(dr("DocumentName"))
cb.Tag = CStr(dr("TemplatePath"))
cb.Name = "chkS" & CStr(dr("StageDocBelongsTo")) & "D" &
CStr(dr("DocumentNumber")) 'ie chkS1D1 Stage 1 Doc 1


Which works fine, but later on I want to reference these created controls
and say change the tag or other properties.
Because the controls don't exist until they are created whilst the program
is running, when I write the code to modify these properties the VB Parser
quite correctly states that the object has not been declared and won't let
me compile the code.

Is there a way that you can write code that references controls that don't
exist until the program is running. The only way I can see to do this is to
put every possible control that might be needed and hide it on the form and
then rather than creating the controls programmatically, just unhide them
and move them to the required location on the form. Which will work, but
kind of defeats what I am trying to do??

Any help appreciated.

Siv
 
J

Jameson

You can store references to them into an array when you create them (or
hash, if you want to be clever, hash them by name, i.e. "combobox1",
"combobox2", then access like this: comboHash("combobox1").Checked, etc.).
 
S

Siv

Thanks for the reply, could you explain it with a simple example, as I am
not sure why what you recommend would not lead to the same problem as I am
having already, i.e. it would give me an object not declared warning?

Does using an array tip the parser off somehow that this isn't an actual
control just yet and will only be when the code runs??

Siv
 
S

SurturZ

You can access the controls by keeping the cb variable in scope. Probably the
easiest is to have a module-level array in the form.

You'll need to use AddHandler if you want to respond to events generated by
the added controls.
 

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