Question Is that possible to determine a variable name in run-time?

pk028382

New member
Joined
Dec 10, 2012
Messages
2
Programming Experience
3-5
I would like to declare some variables which their names are according to the textbox.Text. Is there any simple method to achieve my purpose?
 
You're not talking about variables. If you want to use String values provided by the user at run time then you would use a Dictionary where the keys are Strings. Let's say that you have two TextBoxes on your form: one for the key and one for the value. Your code might look like this:
Private ReadOnly valuesByKey As New Dictionary(Of String, String)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    valuesByKey.Add(keyTextBox.Text, valueTextBox.Text)
End Sub
 
You're not talking about variables. If you want to use String values provided by the user at run time then you would use a Dictionary where the keys are Strings. Let's say that you have two TextBoxes on your form: one for the key and one for the value. Your code might look like this:
Private ReadOnly valuesByKey As New Dictionary(Of String, String)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    valuesByKey.Add(keyTextBox.Text, valueTextBox.Text)
End Sub


In fact, I want to do something like this
VB.NET:
TextBox.Text = "abc"
Dim TextBox.Text as string
But that is an error code.
 
I'm assuming you're doing this... If you have a pre-existing variable, lets say called "varA", and you want to type that into the TextBox, and retrieve the value of whatever varA is at runtime. Then the solution here is Reflection. And to understand the concept of Reflection, you'll have to know exactly where these variables are in the assembly. Are they in the main, usually called, Form1 class? Some predefined class? or elsewhere?

Perhaps it's in a Module? You'll need to provide more information on that.

But this much IS possible. The other way around, dynamically assigning variables in that way, no. It doesn't make any sense either. You'd have to recompile the assembly somehow.
 
Last edited:
Example:
VB.NET:
Public Module VariableContainer
    Public Const obj As String = "This is the value for variable obj, in the VariableContainer class..."
End Module

VB.NET:
Dim obj As FieldInfo = Assembly.GetExecutingAssembly().GetTypes().First(Function(T) T.Name.Contains("VariableContainer")).GetFields().FirstOrDefault(Function(FI) FI.Name = TextBox1.Text)
If obj IsNot Nothing Then
    MessageBox.Show(obj.GetValue(Nothing).ToString)
End If

Now based on the above code, if the text in my TextBox was "obj", it would result as:
0ga2d.png
 
Back
Top