Using a variable to build the name of a variable for assignment

B

Bruce Dumes

Ok, the subject line of this is pretty confusing, I'll admit.

I'm new to dotnet and VB. I've used this kind of construction in Perl a
zillion times over the years.

What I've got is something like this (not my entire code):

<MYCODE>
Sub setVisible(Stage As Integer)

Select Case Stage


Case 2

Panel1.visible = false
Panel2.visible = true
Panel3.visible = false

Case 3

Panel2.visible = false
Panel3.visible = true
Panel4.visible = false

Case 4

Panel3.visible = false
Panel4.visible = true
Panel5.visible = false

Case 5

Panel4.visible = false
Panel5.visible = true
Panel6.visible = false

End Select

End Sub
</MYCODE>

What I'd like is something like this:

<MYBETTERCODE>
Sub setVisible(Stage As Integer)
'If there were an eval, I might do this
eval("Panel" & Stage - 1 & ".visible") = false
eval("Panel" & Stage & ".visible") = true
eval("Panel" & Stage + 1 & ".visible") = false
End Sub
</MYBETTERCODE>

Is there a way to do this in dotnet VB?

Thanks!
 
H

Herfried K. Wagner [MVP]

* Bruce Dumes said:
I'm new to dotnet and VB. I've used this kind of construction in Perl a
zillion times over the years.

What I've got is something like this (not my entire code):

<MYCODE>
Sub setVisible(Stage As Integer)

Select Case Stage


Case 2

Panel1.visible = false
Panel2.visible = true
Panel3.visible = false

Case 3

Panel2.visible = false
Panel3.visible = true
Panel4.visible = false

Case 4

Panel3.visible = false
Panel4.visible = true
Panel5.visible = false

Case 5

Panel4.visible = false
Panel5.visible = true
Panel6.visible = false

End Select

End Sub
</MYCODE>

What I'd like is something like this:

<MYBETTERCODE>
Sub setVisible(Stage As Integer)
'If there were an eval, I might do this
eval("Panel" & Stage - 1 & ".visible") = false
eval("Panel" & Stage & ".visible") = true
eval("Panel" & Stage + 1 & ".visible") = false
End Sub
</MYBETTERCODE>

\\\
Private m_MyPanels() As Panel
..
..
..
m_MyPanels = New Panel() {Panel1, Panel2, ..., Paneln}
..
..
..
Private Sub SetVisible(ByVal Stage As Integer)
m_MyPanels(Stage - 1).Visible = False
...
End Sub
///
 
S

Sven Groot

Bruce said:
<MYBETTERCODE>
Sub setVisible(Stage As Integer)
'If there were an eval, I might do this
eval("Panel" & Stage - 1 & ".visible") = false
eval("Panel" & Stage & ".visible") = true
eval("Panel" & Stage + 1 & ".visible") = false
End Sub
</MYBETTERCODE>

Is there a way to do this in dotnet VB?

Unfortunately no. You could theoretically do something like it using
reflection, but the code would become incredibly complex and convoluted, and
slower as well.
 

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