How do I, if at all possible, reference a variable with another variable
in VB.NET?
For example, if I have a form with a textbox and a button. Type var1 in
the textbox
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button.Click
dim var1 as string
var1 = "Hello World"
msgbox( /// display the contents of var1 using what was entered in
the textbox /// )
End Sub
Is this possible?
You can kind of do it with System.Reflection. However, the variables
you are getting the values of must be public fields of a class. In the
following example, the form has a single text box named TextBox1, and
a button named Button1. The var1, var2, and var3 variables are public
fields of Form1. Reflection is used to get info about the field given
the name typed into TextBox1, and then to get the value of that field
in Me (the current instance of Form1). You should be able to type
"var1" in the text box and press the button to see it's value appear
in the form caption.
There are better ways to check for errors, this is kind of a hack for
less typing, but you might want to just check for a null return from
GetField() instead.
There is no straightforward way to use System.Reflection to get the
value of a local variable, or of a private field.
===
Public Class Form1
' Variables must be public fields of class. They can't be private,
' and they can't be local variables of a method.
Public var1 As Integer
Public var2 As Integer
Public var3 As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
var1 = 111
var2 = 222
var3 = 333
Dim varname As String = TextBox1.Text ' name of variable to
get value of
Try
Dim obj As Object =
GetType(Form1).GetField(varname).GetValue(Me)
Dim val As Integer = CInt(obj) ' val is value of variable
now
Me.Text = val
Catch
' GetType(form1).GetField(varname) is null if varname
unknown, so
' calling GetValue() on that will raise
NullReferenceException.
Me.Text = "Invalid variable name"
End Try
End Sub
End Class
===
HTH,
Jason