Iterate Over all Fields and Properties in an Object with vb.net

Good Morning. Yesterday I was going mad. I needed to get the extended properties (like subject, author etc) of a file but without adding a reference to any new components. If you know how to do this in 1.1 of the Framework I would love to hear from you.

Anyway continuing the same theme as most of this week, we want to iterate over all fields and properties of a an object. This is code for .NET Framework 2.0 or above. Make it a great day!

Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim mlA As New MyLabel
        Dim value As Object
        Dim T As Type = mlA.GetType
        For Each pi As System.Reflection.PropertyInfo In T.GetProperties
            If pi.CanRead AndAlso pi.CanWrite Then
                value = pi.GetValue(mlA, Nothing)
                Debug.Print(pi.Name)
                If Not IsNothing(value) Then
                    Debug.Print(value.ToString)
                End If
                Debug.Print("--------------------")
            End If
        Next
        For Each fi As System.Reflection.FieldInfo In T.GetFields
            Debug.Print(fi.Name)
            value = fi.GetValue(mlA)
            If Not IsNothing(value) Then
                Debug.Print(value.ToString)
            End If
            Debug.Print("--------------------")
        Next
    End Sub
 
End Class
 
Public Class MyLabel
    Inherits Label
 
    Public ContainerDay1 As Integer
    Public ContainerDay2 As Integer
    Public ContainerDay3 As Integer
    Public ContainerDay4 As Integer
    Public ContainerDay5 As Integer
    ' ...
 
End Class
 
Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: