Re: Dynamic creation of controls in vb.net code

From: Ken Tucker [MVP] (vb2ae_at_bellsouth.net)
Date: 02/19/05


Date: Sat, 19 Feb 2005 16:22:53 -0500

Hi,

        You are creating one control over and over again. You dont need
withevents if you use addhandler. Why dont you try something like this

Dim arLabels as new arraylist
dim arButtons as new arraylist

For i = 0 to NumberOfControls
            dim t_Label as label
            T_Label = New Label
            T_Label.Name = "LabelRecord_" & Format(i, "000")
            T_Label.Tag = i
            AddHandler T_Label.DoubleClick, AddressOf DoSomething
AddHandler T_Label.Click, AddressOf DoSomething
            arLabels.add(T_Label)
....
            ' add button
            dim T_Button as button
            T_ButtonDo = New Button
            T_ButtonDo.Name = "ButtonDo_" & Format(i, "000")
             arButton.Add(T_Button)
...

Next

Later in code in a another event I want to access the properties of the
previously created controls again:

For i = 0 to NumberOfControls

' for example
directcast(arButton(i),Button).Text = "Some value"

Next

Ken
--------------------
"Henry" <henryoneal@nospam.nospam> wrote in message
news:FC219D7F-1A59-453F-B3F9-82A3AF16AFF7@microsoft.com...
Hi,

I have to create a variable amount of controls with events for a windows
form in my vb code.

    Private WithEvents T_Label As Label
    Private WithEvents T_ButtonDo As Button

 I create the controls in a loop in load event of the form:

For i = 0 to NumberOfControls

            T_Label = New Label
            T_Label.Name = "LabelRecord_" & Format(i, "000")
            T_Label.Tag = i
            AddHandler T_Label.DoubleClick, AddressOf DoSomething
AddHandler T_Label.Click, AddressOf DoSomething
....
            ' add button
            T_ButtonDo = New Button
            T_ButtonDo.Name = "ButtonDo_" & Format(i, "000")

...

Next

Later in code in a another event I want to access the properties of the
previously created controls again:

For i = 0 to NumberOfControls

' for exambple
T_ButtonDo.Text = "Some value"

Next

The problem is that the code above of course always adresses the last
created control of the Loop in the Load event! How can I adress all controls
created in the loop with their properties and methods ?

Building an array does not solve the problem as I cannot use events together
with an array of controls! And I need the events.

Thanks a lot for help in advance!!!

-- 
Best regards
Henry