r-sniper
r-sniper

Reputation: 1483

Create a variable of name that user defines

I have a textbox that takes only one character input. I want to create a variable of that character.

For e.g.
If user types a in textbox and clicks "Go" button, then it should create a variable of name 'a' of type integer:

Dim a as integer

Upvotes: 0

Views: 55

Answers (1)

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

Assuming you have a Form like this:

The form

Then the code behind could look like:

Public Class Form1

    Private _integerVariables As New Dictionary(Of String, Integer)
    Private _stringVariables As New Dictionary(Of String, String)

    Private Sub btnSaveInteger_Click(sender As Object, e As EventArgs) Handles btnSaveInteger.Click
        Dim newInteger As Integer
        'check if key is there and Text of Value is a valid integer
        If Not String.IsNullOrWhiteSpace(txtIntegerKey.Text) And _
            Integer.TryParse(txtIntegerValue.Text, newInteger) Then
            'check if the key is in the dictionary
            If Not _integerVariables.ContainsKey(txtIntegerKey.Text) Then
                _integerVariables.Add(txtIntegerKey.Text, newInteger)
            Else
                _integerVariables(txtIntegerKey.Text) = newInteger
            End If
        End If
    End Sub

    Private Sub btnSaveString_Click(sender As Object, e As EventArgs) Handles btnSaveString.Click
        'check if key is there
        If Not String.IsNullOrWhiteSpace(txtStringKey.Text) Then
            'check if the key is in the dictionary
            If Not _stringVariables.ContainsKey(txtStringKey.Text) Then
                _stringVariables.Add(txtStringKey.Text, txtStringValue.Text)
            Else
                _stringVariables(txtStringKey.Text) = txtStringValue.Text
            End If
        End If
    End Sub

End Class

Upvotes: 1

Related Questions