Setting the splitter position in the PropertyGrid

rbulph

Junior Contributor
Joined
Feb 17, 2003
Messages
397
I find it a bit irritating that the vertical splitter in the propertygrid control is set to the middle of the control initially and also when the user double clicks on it. If the field names are much longer than the values, they may end up partly obscured while the values have more space than necessary. So I thought I'd have a go at fixing this. I've had partial success in this and I thought I'd post the code here in case either it's of use to anyone else or someone can tell me how to fix the problems that I mention in my comments. In the latter case I would be particularly pleased to hear your suggestions. So here it is - you just need a form with a propertygrid control in it.

Visual Basic:
Imports System
Imports System.Reflection
Imports System.Reflection.Emit
Imports Microsoft.VisualBasic

Public Class Form1
    Private WithEvents g As Control

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        For Each v As Control In Me.PropertyGrid1.Controls
            If TypeName(v) = "PropertyGridView" Then
                g = v
            End If
        Next

        setpropgridobject(Me.PropertyGrid1)

    End Sub

    Private Sub setpropgridobject(ByVal obj As Object)
        Me.PropertyGrid1.SelectedObject = obj
        SetSplitter()
    End Sub

    Private Sub g_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles g.DoubleClick

        'Problem with this is that the splitter gets set in the middle before being set where I want it, 
        'and this is visible.
        If Not g.Cursor Is Cursors.Default Then SetSplitter()

    End Sub

    Private Sub GetLongest(ByVal col As Windows.Forms.GridItemCollection, ByRef r As Integer)

        For Each i As Windows.Forms.GridItem In col
            r = Math.Max(r, TextRenderer.MeasureText(i.Label, Me.PropertyGrid1.Font).Width)
            If i.Expanded Then GetLongest(i.GridItems, r)
        Next

    End Sub

    Private Sub SetSplitter()

        Dim f As Windows.Forms.GridItem = Me.PropertyGrid1.SelectedGridItem
        Do Until f.Parent Is Nothing
            f = f.Parent
        Loop

        Dim r As Integer
        GetLongest(f.GridItems, r)

        Try
            g.GetType.InvokeMember("MoveSplitterTo", Reflection.BindingFlags.InvokeMethod Or _
                   Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance, Nothing, g, New Object() {r + 20})   '20 is determined by trial and error, not very good.

        Catch ex As Exception
            Debug.Print(ex.ToString)
        End Try

    End Sub

End Class
 
Back
Top