Wednesday 24 July 2013

VB Helper: HowTo: Get the values of fields (variables) declared in a form by their names in Visual Basic .NET

VB Helper: HowTo: Get the values of fields (variables) declared in a form by their names in Visual Basic .NET

Private private_value1 As String = "This is private value 1"
Private private_value2 As String = "This is private value 2"
Public public_value1 As String = "This is public value 1"
Public public_value2 As String = "This is public value 2"
Public arr1() As String = {"A", "B", "C"}
Public arr2() As String = {"1", "2", "3"}

Private Sub cboFields_SelectedIndexChanged(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    cboFields.SelectedIndexChanged
    Dim field_info As FieldInfo = _
        Me.GetType().GetField(cboFields.Text, _
        BindingFlags.Instance Or BindingFlags.NonPublic Or _
            BindingFlags.Public)
    If field_info Is Nothing Then
        lblValue.Text = ""
    ElseIf field_info.FieldType.IsArray() Then
        ' Join the array values into a string.
        lblValue.Text = Join(field_info.GetValue(Me))
    Else
        ' Just convert it into a string.
        lblValue.Text = field_info.GetValue(Me).ToString()
    End If
End Sub