Get value of a property with propertyinfo object

719 views Asked by At

Is there a way to get value of a object properties with a propertyinfo object?

psudo code:

propertyinfoObject = Text
myobject.toCommand(propertyinfoObject)

The psudo code above should do the same as

myobject.Text

My goal is to create a simpel Properties form that will work on any object (Later I will use keywords to filter out what options I want the use to see).

My real code

Public Class PropertiesForm
Dim propertyInfoVar() As PropertyInfo
Dim Properties As New Form2
Dim listItem As New ListViewItem
Dim stringarray() As String
Public Sub New(ByRef sender As Object)



    propertyInfoVar = sender.GetType().GetProperties()
    For Each p In propertyInfoVar
        stringarray = {p.Name.ToString, #INSERT VALUE SOMEHOW HERE#}

        listItem = New ListViewItem(stringarray)
        Properties.ListView1.Items.Add(listItem)
    Next
    Properties.Visible = True
End Sub

EDIT Just use propertyGrid as suggested below!

1

There are 1 answers

0
Ňɏssa Pøngjǣrdenlarp On

The standard PropertyGrid already does all that for you. Filtering properties is not so obvious, here's how:

The control includes a BrowsableAttributes property which allows you to specify that only properties with the specified attribute value should be shown. You can use existing attributes, or custom ones. This is specifically for tagging visible props:

<AttributeUsage(AttributeTargets.Property)>
Public Class PropertyGridBrowsableAttribute
    Inherits Attribute

    Public Property Browsable As Boolean

    Public Sub New(b As Boolean)
        Browsable = b
    End Sub
End Class

Apply it to an Employee class to hide pay rates or anything else:

Public Class Employee
    <PropertyGridBrowsable(True)>
    Public Property FirstName As String
    ...
    <PropertyGridBrowsable(False)>
    Public Property PayRate As Decimal
    <PropertyGridBrowsable(False)>
    Public Property NationalInsuranceNumber As String

Test code:

Dim emp As New Employee With {.Dept = EmpDept.Manager,
                                    .FirstName = "Ziggy",
                                    .PayRate = 568.98D,
                                     ...
                                    .NationalInsuranceNumber = "1234567"
                                   }

propGrid.BrowsableAttributes = New AttributeCollection(New PropertyGridBrowsableAttribute(True))

propGrid.SelectedObject = emp

enter image description here

BrowsableAttributes is a collection, so you can add several.