Search code examples
c#.netwinformspropertygrid

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?


Solution

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

    public static GridItemCollection GetAllGridEntries(this PropertyGrid grid)
    {
        if (grid == null)
            throw new ArgumentNullException("grid");
    
        var field = grid.GetType().GetField("gridView", BindingFlags.NonPublic | BindingFlags.Instance);
        if (field == null)
        {
            field = grid.GetType().GetField("_gridView", BindingFlags.NonPublic | BindingFlags.Instance);
            if (field == null)
                return null;
        }
    
        var view = field.GetValue(grid);
        if (view == null)
            return null;
    
        try
        {
            return (GridItemCollection)view.GetType().InvokeMember("GetAllGridEntries", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, view, null);
        }
        catch
        {
            return 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.