views:

144

answers:

2

Hi everyone!

I'm faced with a couple of problems in VB.net: 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")

+2  A: 

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
       Get
           Return "Foo!"
       End Get
    End Property

    Property Bar As String
       Get
           Return "Ar!"
       End Get
       Set
           ' 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
           Console.WriteLine(prop.Name)
           If Not prop.CanWrite
               Console.WriteLine("   (Read only)")
           End If
       Next prop
   End Sub

End Class
Jon Skeet
Thanks Jon, quick and clear, just what I was looking for. Answer accepted!
Master_T
A: 

Here's how you loop over the properties in MyObject. As Jon Skeet says, check for CanWrite to help you with the second part of your question:

        Dim MyProperties As System.Reflection.PropertyInfo() = MyObject.GetType().GetProperties()
        For Each prop As System.Reflection.PropertyInfo In MyProperties
                If prop.CanWrite Then
                    //do stuff
                End If
        Next
hawbsl