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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With