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?
Yes, you could use reflection for that.
http://msdn2.microsoft.com/en-us/library/system.type.getproperty.aspx

Signature
Tim Wilson
.NET Compact Framework MVP
> I have an object with 30+ exposed properties. How can I, based on a string
> input, retrieve the value of a specific property?
[quoted text clipped - 9 lines]
>
> There's got to be a better way then this. Is Reflection what I'm after?
Karl Pierburg - 22 Mar 2006 15:38 GMT
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
> Yes, you could use reflection for that.
> http://msdn2.microsoft.com/en-us/library/system.type.getproperty.aspx
[quoted text clipped - 13 lines]
> >
> > There's got to be a better way then this. Is Reflection what I'm after?
Tim Wilson - 22 Mar 2006 18:31 GMT
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

Signature
Tim Wilson
.NET Compact Framework MVP
> Ok...I think I see where this is going, but I'm still having some issues.
>
[quoted text clipped - 26 lines]
> > >
> > > There's got to be a better way then this. Is Reflection what I'm after?