Search code examples
c#.netvisual-studiopropertygridgridsplitter

How do you programmatically adjust the horizontal divider of a PropertyGrid control?


I am using a .NET PropertyGrid control in my C# project.

When the form containing the grid loads, the horizontal splitter (which divides the Settings from the Description) is at a default position. How do I change the position of that splitter programmatically in C#?


Solution

  • This code is based off of an article (http://www.codeproject.com/KB/grid/GridDescriptionHeight.aspx) from The Code Project, with two fixes and some cleanup introduced.

    private void ResizeDescriptionArea(PropertyGrid grid, int lines)
    {
        try
        {
            var info = grid.GetType().GetProperty("Controls");
            var collection = (Control.ControlCollection)info.GetValue(grid, null);
    
            foreach (var control in collection)
            {
                var type = control.GetType();
    
                if ("DocComment" == type.Name)
                {
                    const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;
                    var field = type.BaseType.GetField("userSized", Flags);
                    field.SetValue(control, true);
    
                    info = type.GetProperty("Lines");
                    info.SetValue(control, lines, null);
    
                    grid.HelpVisible = true;
                    break;
                }
            }
        }
    
        catch (Exception ex)
        {
            Trace.WriteLine(ex);
        }
    }
    

    I've used it in my own projects; it should work fine for you.