Avatar of jellydeal
jellydeal
 asked on

How to reference a dynamically created object in vb.net

HI..

I have created various panels using :

 Dim panel1 As New Panel()
        Dim height = 50
        Dim parent_width = staff_panel_list2.Width
        staff_panel_list2.Height = height * staff_list_counter
        panel1.Name = "staff" & staff_list_counter
        panel1.Size = New Size(parent_width, height)
        panel1.Location = New Point(0, 0 + (height * (staff_list_counter - 1)))
        panel1.Controls.Add(label1)
        staff_panel_list2.Controls.Add(panel1)

Which works fine.. panels stacked within the staff_panel_list2 panel.

I now need to be able to reference the stacked panels eg:

staff1.visible=false
but I need to be able to do it programatically like :
("staff" & counter).visible=false

Is there a way to do this?
thanks
Visual Basic.NET

Avatar of undefined
Last Comment
nepaluz

8/22/2022 - Mon
nepaluz

You can not use variables like that. Give your panels names, e.g
Panel1.Name = "Panel1"

Open in new window

, then you can iterate through the controls like:
For Each x As Control In Me.Controls
   If x.Name = "staff" & counter Then x.Visible = False
End If

Open in new window

jellydeal

ASKER
Is there a way I can reference the panel directly using a variable for its name, similar to javascript though, like :

cnt=1
panel & cnt.visible=false

I see how youw way can work but I dont want to have to loop through all controls every time.

thanks
Mike Tomlinson

You can use a Dictionary with the Panel name as the key:

    Private pnls as New Dictionary(Of String, Panel)
   
    ...
        pnls.Add(panel1.Name, panel1)

Later, you can do:

    pnls("panel1").xxx = yyy

See Dictionary:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER CERTIFIED SOLUTION
nepaluz

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.