.NET PropertyGrid -> How to set column width and description window height

23 10 2007

You would think that setting the column width in a property grid is easy, right?  Wrong!
This took me a little while to work out (thanks reflector!), but it was worth it in the end.


 Public Shared Function RunInstanceMethod(ByVal t As System.Type, ByVal strMethod As String, ByVal objInstance As Object, ByVal aobjParams As Object()) As Object
  Dim eFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.NonPublic
  Return RunMethod(t, strMethod, objInstance, aobjParams, eFlags)
  End Function
  'end of method
  Private Shared Function RunMethod(ByVal t As System.Type, ByVal strMethod As String, ByVal objInstance As Object, ByVal aobjParams As Object(), ByVal eFlags As BindingFlags) As Object
  Dim m As MethodInfo
  Try
  m = t.GetMethod(strMethod, eFlags)
  If m Is Nothing Then
  Throw New ArgumentException("There is no method '" + strMethod + "' for type '" + t.ToString() + "'.")
  End If
Dim objRet As Object = m.Invoke(objInstance, aobjParams)
  Return objRet
  Catch
  Throw
  End Try
  End Function
 Private Sub SetDescriptionWindowSize(ByVal size As Integer)
  Dim controlsProp As PropertyInfo = PropertyGrid1.[GetType]().GetProperty("Controls")
  Dim cc As Control.ControlCollection = DirectCast(controlsProp.GetValue(PropertyGrid1, Nothing), Control.ControlCollection)
  For Each c As Control In cc
  Dim controlType As Type = c.[GetType]()
  If controlType.Name = "DocComment" Then
  Dim linesProperty As PropertyInfo = controlType.GetProperty("Lines")
  linesProperty.SetValue(c, size, Nothing)
  Dim userSizedField As FieldInfo = controlType.BaseType.GetField("userSized", BindingFlags.Instance Or BindingFlags.NonPublic)
  userSizedField.SetValue(c, True)
  Exit For
  End If
  Next
  End Sub

Private Sub SetPropertyGridColumnWidth(ByVal width As Integer)
  Dim grid As Control = PropertyGrid1
  Dim propertyGridView As Control = grid.Controls(2)
  Dim propertyGridViewType As Type = propertyGridView.[GetType]()
  RunInstanceMethod(propertyGridViewType, "MoveSplitterTo", propertyGridView, New Object() {width})
  End Sub


Actions

Information

Leave a comment