Prevent column resizing in the .NET Winforms DataGrid

Derive a new DataGrid and override the OnMouseDown method to see what portion of the grid was clicked. If it was the ColumnResize area, do not call the base class' OnMouseDown method. A new AllowColumnResizing property is added to the grid so resizing can be toggled on and off.

Add this module level variable:

    ' Column resizing flag.
    Private myAllowColumnResizing As Boolean = True

Add this property:

    Public Property AllowColumnResizing() As Boolean
        '
        ' Get/set property indicating if columns can be resized.
        '
        Get
            AllowColumnResizing = myAllowColumnResizing
        End Get

        Set(ByVal theValue As Boolean)
            myAllowColumnResizing = theValue
        End Set

    End Property

Override this method:

    Protected Overloads Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
        On Error Resume Next

        Dim aHitTestInfo As DataGrid.HitTestInfo
        aHitTestInfo = Me.HitTest(New Point(e.X, e.Y))
        '
        ' Column resizing.
        '
        If (aHitTestInfo.Type = Me.HitTestType.ColumnResize) Then
            If myAllowColumnResizing Then
                MyBase.OnMouseDown(e)
            End If
        End If

        MyBase.OnMouseDown(e)
    End Sub

Similarly, you can disable Row resizing.




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page