Dynamically Access Control

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have 26 different panels. I'd like to access their properties dynamcially,
determined by which "spot" is selected. Here's what I've thought of...

Private Function getSpot(ByVal spot As Int16) As Control
Select Case spot
Case 0
Return Me.pnl0
Case 1
Return Me.pnl1
Case 2
Return Me.pnl2
Case 3
Return Me.pnl3
Case 4
Return Me.pnl4
Case 5
Return Me.pnl5
Case 6
Return Me.pnl6
End Select
Return Nothing
End Function

.... as you can see, the panels are named in sequence. is there a better way
to do this? i.e. (me.panel & spot) ...

Thanks!

Casey
 
I can think of 3 options you have:

1. Create a hashtable and map each control to the value you'll want to look
them up by at runtime.

2. Create the controls in an array and manually place each on the form
(don't use the VS designer). Then you can do a simple array lookup to return
the right control.

3. Do a brute force lookup like you have right now. An alternative way to do
this (from the code you have) is to run a foreach on your Form.Controls and
return the one that matches the name you're looking for. It might look
something like this (I'm not a VB coder by nature):
Dim name As String = String.Format("pnl{0}", spot)

Dim c As Control

For Each c In Me.Controls

If c.Name = name Then

Return c

End If

Next

Return Nothing
 
Back
Top