Wine Too
Wine Too

Reputation: 4655

Subclassing DataGridView

I have need to subclass a DataGridView to get certain functionality which is needed for all DataGridViews across my solution.

For that I make those sample code:

Imports System.ComponentModel

Public Class xDataGridView
Inherits DataGridView

Protected Overrides Sub onKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
    If e.Control Then
        If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then
            e.Handled = True
        End If
    End If
End Sub

Protected Overrides Sub onMouseDown(ByVal e As MouseEventArgs)
' part of code for drag/drop
    fromindex = Me.HitTest(e.X, e.Y).RowIndex
    If fromindex > -1 Then
        Dim dragSize As Size = SystemInformation.DragSize
        dragrect = New Rectangle(New Point(CInt(e.X - (dragSize.Width / 2)), CInt(e.Y - (dragSize.Height / 2))), dragSize)
    Else
        dragrect = Rectangle.Empty
    End If
End Sub

With onKeyDown I terminate builtin functionality for Ctrl+Up to GO HOME and with Ctrl+Down to GO END of grid. With onMouseDown I do common code for drag and drop.

All of that actually work OK except that my events _KeyDown and _MouseDown on main program in which is this class included are never fired! If I remove those code from class then events in main program ARE fired as expected.

1) What I do wrong and how to get _KeyDown and _MouseDown in main program to be fired after those in class.

2) How to get rid of DataGridView's built in functionality Ctrl+Click?

Upvotes: 0

Views: 599

Answers (1)

Hans Passant
Hans Passant

Reputation: 942508

A hard requirement whenever you override the OnXxx method for an event is to call the base class method. Failure to do so will cause various kind of mishaps (DGV already overrides many of these methods), it ultimately prevents the corresponding event from being fired. So fixing the first one:

Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
    If e.Control Then
        If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then
            e.Handled = True
            Return               '' added
        End If
    End If
    MyBase.OnKeyDown(e)          '' added
End Sub

Note how IntelliSense helps you fall in the pit of success, it auto-generates the MyBase call.

Upvotes: 4

Related Questions