Disable the .NET DataGrid's TAB, Arrow, Home/End, Page Up and Page Down keys

Derive a new DataGrid and override the ProcessCmdKey method to trap for the various navigation keys.

Add this module level variable:

    ' Disable all navigation keys.
    Private myDisableAllNavKeys As Boolean = False

Add this property:

    Public Property DisableAllNavKeys() As Boolean
        ' Get/set property indicating if naviagation keys are allowed.
            DisableAllNavKeys = myDisableAllNavKeys
        End Get

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

    End Property

Override this method:

    Protected Overrides Function ProcessCmdKey(_
            ByRef msg As System.Windows.Forms.Message, _
            ByVal keyData As System.Windows.Forms.Keys) As Boolean
        ' Disable the navigation keys.
        On Error Resume Next

        If myDisableAllNavKeys Then
            Select Case msg.WParam.ToInt32()

                Case CInt(Keys.Down)
                    Return True

                Case CInt(Keys.Up)
                    Return True

                Case CInt(Keys.Right)
                    Return True

                Case CInt(Keys.Left)
                    Return True

                Case CInt(Keys.PageDown)
                    Return True

                Case CInt(Keys.PageUp)
                    Return True

                Case CInt(Keys.Home)
                    Return True

                Case CInt(Keys.End)
                    Return True

                Case CInt(Keys.Tab)
                    Return True
            End Select
        End If

        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

Now all you need to do is set your derived grid's DisableAllNavKeys property. In real life I use multiple properties so I can disable individual keys such as the TAB key, groups of keys such as the arrow keys, all keys,...

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