Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate PropertyGrid items?

I have a PropertyGrid with assigned to it some object.

var prpGrid = new PropertyGrid();
prp.SelectedObject = myObject;

I want to get all grid items like I can get selectedGridItem property:

var selectedProperty = prpGrid.SelectedGridItem;

Can I do this?

like image 483
Yuriy Avatar asked Mar 02 '11 14:03

Yuriy


2 Answers

Here is a piece of code that will retrieve all GridItem objects of a property grid:

public static GridItemCollection GetAllGridEntries(PropertyGrid grid)
{
    if (grid == null)
        throw new ArgumentNullException("grid");

    object view = grid.GetType().GetField("gridView", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(grid);
    return (GridItemCollection)view.GetType().InvokeMember("GetAllGridEntries", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, view, null);
}

Of course, since this is using an undocumented private field of the Property Grid, is not guaranteed to work in the future :-)

Once you have all the GridItems, you can filter them using the GridItem.GridItemType property.

like image 196
Simon Mourier Avatar answered Nov 05 '22 02:11

Simon Mourier


If you only need the object's properties, you can get those via Reflection:

PropertyDescriptorCollection myObjectProperties = TypeDescriptor.GetProperties(myObject);

If you did hide some of the properties with BrowsableAttribute(false), you can use GetProperties(Type, Attribute[]) to filter those out.

I am not aware of a method that returns a GridItem collection.

Update
Of course you can also obtain the string that the PropertyGrid uses for the labels via Reflection.
If you did decorate the property with DisplayNameAttribute("ABC"), you should be able to access DisplayName via GetCustomAttributes(Type, Boolean). Otherwise just use the Name of the PropertyDescriptor.

like image 36
Thomas Zoechling Avatar answered Nov 05 '22 01:11

Thomas Zoechling