Extending DataGridView class with new behavior

jcortrig

Member
Joined
Sep 8, 2009
Messages
6
Programming Experience
5-10
Hello...

I'm hoping someone can help me with what I think is a fairly simple problem. I'd like to write a class that inherits from DataGridView that I can drop on forms with some simple changes. One of the things I'd like to do is to have the user pressing the [enter] key trigger the same behavior as the "CellDoubleClick" event.

So, what's the best way of doing that? In code, this is basically what I'm after. The commented out line doesn't work, it's just the gist of what I want to do.

Thanks!

VB.NET:
Public Class DataGridViewExtension
    Inherits DataGridView

    Private Shadows Sub PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles MyBase.PreviewKeyDown
        If e.KeyCode = Keys.Enter Then
            ' MyBase.CellDoubleClick(sender, Nothing)
        End If
    End Sub

End Class
 
Not exactly sure what you mean by CellDoubleClick event, but if you want to start editing with Enter you can change the EditMode property, default is EditOnKeyStrokeOrF2 and you can also select EditOnEnter.

...on second thought I think I see what you mean. What you can do is to handle the KeyUp event and check for Enter key
VB.NET:
If e.KeyCode = Keys.Enter Then
Then call your method. In this method you can refer to the CurrentCell.
This will work when navigating the grid, but not in edit mode when the editing control has focus and Enter key has a different purpose.
 
Thanks for your reply. I think I need to explain myself more clearly.

The application I'm working on consists of a lot of data entry. Particular fields have search capabilities built into them, where a child form pops up with the results and the user can double-click one of those cells to select that specific result to populate the field. (e.g. Customer address, can select which address they want from the grid/list by double-clicking it, that populates fields back on the parent form)

I'm wanting to create a class that extends the DataGridView that will allow the user to hit [enter] with the row highlighted, and call the same code that double-clicking a row/cell does.

It is also important to note that the implementation of the double-click events (as it is currently coded and working) varies from one grid object to the next.
 
You can't raise a base class event from inherited classes, you can however define your own event, that you raise upon the DGVs CellDoubleClick and KeyUp events.
 
Yeah, I had come to a similar conclusion. Then I can just handle the event in each sub-form with the proper implementation.

Thanks!
 
Back
Top