Using string as a name of a variable

前端 未结 3 2017
走了就别回头了
走了就别回头了 2021-01-21 07:22

Is it possible to use a string as a name of a variable? For Example..
I declared x as a private double

 Private TextBox1Store,TextBox2Store,TextBox3Store A         


        
相关标签:
3条回答
  • 2021-01-21 07:58

    Can you use a Dictionary(Of String, Double)?

    Private values As New Dictionary(Of String, Double)
    
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        setValue(sender)
    End Sub
    
    Private Sub setValue(sender As Object)
        Dim tb As TextBox = CType(sender, TextBox)
        Dim tbName As String = tb.Name & "Strore"
        If Not values.ContainsKey(tbName) Then
            values.Add(tbName, tb.Text)
        Else
            values(tbName) = tb.Text
        End If
    End Sub
    
    Private Function getValue(sender As Object) As Double
        Dim tbName As String = CType(sender, TextBox).Name & "Strore"
        If Not values.ContainsKey(tbName) Then
            Return Double.NaN
        Else
            Return values(tbName)
        End If
    End Function
    
    0 讨论(0)
  • 2021-01-21 08:07

    Just do this:

    Dim tb As TextBox = CType(sender, TextBox)
    Me.Controls(tb.Name & "Store") = mqtyCalc(CInt(someVariable.Text), CInt(Label1.Text))
    

    I strongly suggest you a couple of things. First, enable Option Strict On in you project properties, as it will improve your programming practices. And, as you can see in my code, concatenate strings with & instead of + in VB.NET.

    0 讨论(0)
  • 2021-01-21 08:17

    I would like to share the code that I am using. Hope this helps future viewers of this question.

    Dim tb As TextBox = sender
    Dim tempObjNm As String
    tempObjNm =    tb.Name + "Strore"
    Me.GetType.GetField(tempObjNm).SetValue(Me, CType(mqtyCalc(someVariable.Text, Label1.Text), Double))
    
    0 讨论(0)
提交回复
热议问题