创建用户定义的名称变量

时间:2015-03-18 14:17:16

标签: vb.net textbox

我有textbox,只需输入一个字符。我想创建一个该角色的变量。

例如 如果用户在文本框中键入a并单击“开始”按钮,则应创建一个名为“a”的变量,类型为整数:

Dim a as integer

1 个答案:

答案 0 :(得分:1)

假设你有一个这样的表格:

The form

然后背后的代码可能如下:

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