Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 607
Ali Ahmadi Avatar asked Sep 16 '12 13:09

Ali Ahmadi


2 Answers

2019 Answer

Other answers on this page contain adhoc improvements over the course of C# versions and user comments.

I picked the best working solution and created an Extension method.

public static class PropGridExtensions
{
    public static void SetLabelColumnWidth(this PropertyGrid grid, int width)
    {
        FieldInfo fi = grid?.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic);
        Control view = fi?.GetValue(grid) as Control;
        MethodInfo mi = view?.GetType().GetMethod("MoveSplitterTo", BindingFlags.Instance | BindingFlags.NonPublic);
        mi?.Invoke(view, new object[] { width });
    }
}

Usage:

In Form_Load() event, call it directly on your property grid like so:

myPropertyGrid.SetLabelColumnWidth(value);

You shouldn't need to call it anywhere else. Call once and enjoy.

like image 164
JamesHoux Avatar answered Sep 25 '22 23:09

JamesHoux


Version for Framework 4.0 (I had to use BaseType). Method is used in class inherited from PropertyGrid:

private void SetLabelColumnWidth(int width)
{
    FieldInfo fi = this.GetType().BaseType.GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic);
    object view = fi.GetValue(this);
    MethodInfo mi = view.GetType().GetMethod("MoveSplitterTo", BindingFlags.Instance | BindingFlags.NonPublic);

    mi.Invoke(view, new object[] { width });
}
like image 28
SilentiumUniversi Avatar answered Sep 25 '22 23:09

SilentiumUniversi