gspeedtech
gspeedtech

Reputation: 57

How do you return the value of a Property in a custom class

I have a custom vb,net class named Location with multiple properties.

Example

Class = Location

Property = Street

Value = "Main St"

Property = City

Value = "AnyTown"

Property = Country

Value = "USA"

Through reflection I can get the names of each property:

Public Function GetLocationValue(ByRef sLocation)    
Dim sTable As New ProjectSchema.Location
sTable = sLocation
For Each p As System.Reflection.PropertyInfo In sTable.GetType().GetProperties()
        If p.CanRead Then
           Console.WriteLine(p.Name)
        End If
Next
End Function

Results:

p.Name = Street

p.Name = City

p.Name = Country

How can I get the value of each p.Name and return "Main St", "AnyTown" o "USA"

Upvotes: 1

Views: 1633

Answers (2)

agent-j
agent-j

Reputation: 27943

Where p is your PropertyInfo object.

p.GetValue (sTable, Nothing)

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564861

You just have to get the value from the property info:

Dim val as Object
For Each p As System.Reflection.PropertyInfo In sTable.GetType().GetProperties()
    If p.CanRead Then
       Console.WriteLine(p.Name)
       val = p.GetValue(sTable, Nothing)
       Console.WriteLine(val)
    End If
Next

Upvotes: 5

Related Questions