Search code examples
c#.netwinformspropertygrid

How can I set the column width of a Property Grid?


I am using property grid in my application to display the name and value of the properties of an object.

By default the width of the columns (name and property) are at a ratio of 50:50. and we have an option of sliding the splitter to change this width. I would like to know how this width can be adjusted programmatically so that it can be set at say 25:75.


Solution

  • As in this answer is mentioned :

    There is no property to do that and you have to hack the control. first add this code :

        public static void SetLabelColumnWidth(PropertyGrid grid, int width)
    {
        if (grid == null)
            throw new ArgumentNullException("grid");
    
        // get the grid view
        Control view = (Control)grid.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(grid);
    
        // set label width
        FieldInfo fi = view.GetType().GetField("labelWidth", BindingFlags.Instance | BindingFlags.NonPublic);
        fi.SetValue(view, width);
    
        // refresh
        view.Invalidate();
    }
    

    and call it with the size what you want . like this:

    SetLabelColumnWidth(propertyGrid1, 100);