Master_T Master_T - 1 year ago 46 Question

Listing Properties / Checking if a Property is ReadOnly

I'm faced with a couple of problems in I have a series of objects, which properties I'm displaying in a grid for the user to edit.

My first problem is: how do I get a list of all the properties of an object? Is it even possible? The datagrid control that I'm using accepts string values with the name of the property as parameters, but inserting them manually would be a real problem, because there are a LOT of them. So: is there a way to get a list of strings with the name of each property of an object?

If that's possible, here comes the second question:
Now, of course, since users are editing the properties, I'm not interested in showing ReadOnly properties which they cannot edit. Hence my secodn problem: is there a way to check if a property is readonly at runtime?

Thanks in advance for any help you can give (even if it's just a "it can't be done")

Answer Source

You can do this with reflection. Use foo.GetType() to get the type of a particular object. Then use Type.GetProperties() to find all the properties. For each property you can find out whether it's writable using PropertyInfo.CanWrite.

Here's a simple example:

Option Strict On
Imports System
Imports System.Reflection

Public class Sample

    ReadOnly Property Foo As String
           Return "Foo!"
       End Get
    End Property

    Property Bar As String
           Return "Ar!"
       End Get
           ' Ignored in sample
       End Set
    End Property

End Class

Public Class Test

   Public Shared Sub Main()
       Dim s As Sample = New Sample()

       Dim t As Type = s.GetType()
       For Each prop As PropertyInfo in t.GetProperties
           If Not prop.CanWrite
               Console.WriteLine("   (Read only)")
           End If
       Next prop
   End Sub

End Class