Iterating Through Properties
In this code snippet we have a custom object that contains a method called GetProperties. The purpose of this method is so the object can return an arraylist of all the named properties it contains. Again you could use this to populate a drop down which then adds fields to be reported on or calculated against.
Public Function GetProperties() As ArrayList
Dim Properties As New ArrayList
Dim PropertyInfo As PropertyInfo() = Me.GetType.GetProperties()
Dim PropertyItem As PropertyInfo
For Each PropertyItem In PropertyInfo
Properties.Add(PropertyItem.Name)
Next
Return Properties
End Function
You can see we use the PropertyInfo object and then used the method GetProperties. This returns an array type which we can then iterate through and build an arraylist that the object will return containing all the named properties it contains.
Setting the Value of a Named Property
In this next method we provide code on how to set the value of a named property at run time. For example, say we used the previous method to obtain a list of named properties, and now we want to set the value of the property for our object.
Public Sub SetProperty(ByVal PropertyName As String, _
ByVal PropertyValue As String)
Dim userType As Type = Me.GetType()
Dim UserProp As PropertyInfo = userType.GetProperty(PropertyName)
UserProp.SetValue(Me, PropertyValue, Nothing)
End Sub
As you can see again we use PropertyInfo, get the property of the object and pass the current object which in this example is a custom user object. Then pass the value we want the property to contain.
Get the Value of a Named Property
In the next code block, we'll obtain the value of a named property at runtime for our custom object.
Public Function GetPropertyByNamedValue(ByVal PropertyName As _
String)
Dim userType As Type = Me.GetType()
Dim UserProp As PropertyInfo = userType.GetProperty(PropertyName)
Dim myValue As String
myValue = UserProp.GetValue(Me, Nothing)
Return myValue
End Function
Basically a similar method here, again using the PropertyInfo class and then calling the GetValue method passing our custom object, and returning the value we specified when first instantiating the PropertyInfo class.