How can I set the column width of a Property Grid?
I found that the solution of hamed doesn't work reliably. I have solved it by programmatically simulating the user dragging the column splitter. The following code uses reflection to do this:
public static void SetLabelColumnWidth(PropertyGrid grid, int width)
{
if(grid == null)
return;
FieldInfo fi = grid.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic);
if(fi == null)
return;
Control view = fi.GetValue(grid) as Control;
if(view == null)
return;
MethodInfo mi = view.GetType().GetMethod("MoveSplitterTo", BindingFlags.Instance | BindingFlags.NonPublic);
if(mi == null)
return;
mi.Invoke(view, new object[] { width });
}
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.