• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

How to reference a dynamically created object in vb.net


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)))

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

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

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

Is there a way to do this?
  • 2
1 Solution
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

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

panel & cnt.visible=false

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

Mike TomlinsonMiddle School Assistant TeacherCommented:
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:
The only way I can think of without overtly looping through is by LINQ (which actually loops in the background!)
Dim gf = From x As Control In Me.Controls Where TypeOf x Is Panel AndAlso x.Name = "staff" & counter Select x.Visible = False

Open in new window

where you have counter defined as a variable
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now