Avatar of Merlin_UK
 asked on

How to obtain the values of all the properties in an object

I'm trying to obtain all the values of all the properties of an object (class) and can find the names of the properties without a problem, but  I'm having trouble getting the values of the properties

I've tried the following

    Public Sub test()
        Dim col As PropertyDescriptorCollection = TypeDescriptor.GetProperties(myCustomClass)
        Dim cNew As PropertyDescriptor
        For Each cls As PropertyDescriptor In col
            Dim sName As String = cls.Name
            Dim oValue As Object = cls.GetValue(cls).ToString
    End Sub

But keep getting errors on GetValue()

Any help would be appreciated.
Visual Basic.NET

Avatar of undefined
Last Comment

8/22/2022 - Mon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Fernando Soto

Try it this way

   Dim oValue As Object = cls.GetValue(myCustomClass)
Jayadev Nair

Hi Merlin,

The code you have written will work if you the change the line where the error occurs. In that line you specified cls as the component object i.e.

Dim oValue As Object = cls.GetValue(cls).ToString

From which you wanna retrieve the value of that property. Instead of cls, supply the instance from which you need the value. The correction is,

Dim oValue As Object = cls.GetValue(MyObject).ToString

The GetValue method needs the instance as its parameter.


Thanks to all
I've given the points to Zeon because he was first but also
it is a very elegant answer
I had a feeling I should be going about this slightly different
and Zeon's answer proved it
Thanks to Fernando and compued
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck