Trapping each key press in a datagridview

J Trahair

Well-known member
Joined
May 14, 2008
Messages
175
Location
Spain
Programming Experience
10+
I want to trap each keypress a user makes when he is typing a word into a cell. DGVs don't seem to have KeyPress or KeyPressEdit. It directs me to EditingControlShowing. However, this only seems to fire on leaving the cell.

Is there a way of getting each letter in the word being typed, the moment it is typed?

I want to investigate rolling my own 'Google' style dropdown box, filled with a whole phrase predictively based on the letters typed so far without exiting the cell.
 
You can use the editing controls events: Control Events (System.Windows.Forms) (like KeyDown/KeyPress/KeyUp)
The link I posted also said this:
For example, you can handle the EditingControlShowing event to attach event-handlers to the events of the editing control.
 
A productivity tip: Since there is only ever one editing control active you can declare a WithEvents variable and set up the event handler you need for that (use the objects/events drop downs in code editor). From EditingControlShowing event just assign e.Control to your variable. No need to add/remove handlers in code.
 
Here's how I did it:

VB.NET:
    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean

        If keyData = 32 Or (keyData >= 48 And keyData <= 57) Or (keyData >= 65 And keyData <= 90) Or (keyData >= 97 And keyData <= 122) Then
            gstrGrd1SQL = gstrGrd1SQL & Chr(keyData)
            Call FindRecordFromGrd1SQL()
        End If

        'Return MyBase.ProcessCmdKey(msg, keyData)

    End Function

As each key press occurs (filtered for alpha numerics only), it adds the letters typed, one at a time, to gstrGrd1SQL which, each time a letter is added, goes to a simple database SQL query which produces fewer and more accurate predictive choices, the more characters there are in gstrGrd1SQL. All I need do now is prevent or trap key presses from other text boxes, combobox etc, and to exclude SQL look-ups when Len(gstrGrd1SQL) < 3 or 4.

Thank you.
 
Back
Top