Dynamically Determining an Objects Property

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have an object with 30+ exposed properties. How can I, based on a string
input, retrieve the value of a specific property?

Here's what I'm doing right now:

Function GetField(ByVal FieldName as String) as String
Select Case FieldName
Case "Field1" Return myObj.Field1
Case "Field2" Return myobj.Field2
END Select
End Function

There's got to be a better way then this. Is Reflection what I'm after?
 
Ok...I think I see where this is going, but I'm still having some issues.

I can do the following:

myObj.GetType.GetProperty("FirstName")

This Returns a PropertyInfo object. But I can't seem to setup the
"GetValue" method to return the actual string.

Where am I going wrong?

KP
 
Assuming that you're looking for a public property of type string, you can
do something like this...

Dim info As PropertyInfo = Me.Button1.GetType().GetProperty("Text")
If (Not info Is Nothing) Then
Dim obj As Object = info.GetValue(Me.Button1, Nothing)
If (TypeOf obj Is String) Then
MessageBox.Show(Convert.ToString(obj))
End If
End If
 
Back
Top