Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can't Trap Return Key on DataGridView Control

Status
Not open for further replies.

tadd

Programmer
Oct 28, 2001
70
US

I need to execute some code when the user presses the ENTER key on a DataGridView control. However, it seems that the ENTER key is preprocessed by the control, and is not passed on to the KeyDown event.

Anyone know how to interupt this pre-processing, so that the ENTER key can be handled?

I suspect I have to override a method somehow, but I'm not exactly sure what to do ...I'm looking for an example that shows specifically how to do this.

Any help is greatly appreciated.
 
Write code in KeyDown Event handler:

Code:
    Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
        If e.KeyCode = Keys.Enter Then
          ' code here!
        End If
    End Sub
 
Thanks TipGiver for your reply.

Your suggested code works fine, of course. However, I realized that I left out one important detail in my original post. My mistake. Here goes:

Try editing a cell value, and then pressing RETURN. It seems that after editing a cell value, the RETURN key is NOT passed to the KeyDown() event. Give it a try and let me know what happens.

Thanks!
 

I had tried that too. Turns out (again) I need to provide more details about what I am trying to do...

The code that I need to execute needs to advance the currently selected cell by 2 rows (instead of the standard 1 row) when the user makes a change to a cell and then presses ENTER. Here's a simplified example of what I am talking about. I will put my code in CellEndEdit(), like you suggested:


Sub DataGrid_CellEndEdit()

Dim CurCol as Short = DataGrid.SelectedCells(0).ColIndex
Dim CurRow as Short = DataGrid.SelectedCells(0).RowIndex

CurRow +=2

'This has no effect when called from this event!
DataGrid.Item(CurCol, CurRow).Selected = True

End Sub


Try and see if it works for you. The last line has no effect for me.

I know the next thing you are going to tell me to try is to put the code under the CellValidating() event. Unfortunately, that caused a stack fault due to an infinite loop. Changing the current cell in the CellValidating() event causes CellValidating() to be called again, which changes the cell, which causes CellValidating() to be called, which changes the cell, etc. etc.

I suppose there is some way I could prevent the recursion...let me think about it...in the meantime, if you have any good ideas let me know...

I appreciate your help...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top