Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleChange the way a DataGridView control navigates when the user presses the Enter key in Visual Basic 2005
DescriptionThis example shows how to change the way a DataGridView control navigates when the user presses the Enter key in Visual Basic 2005.
KeywordsDataGridView, Enter, Return, navigate, focus, cell, row, column, Visual Basic 2005, VB 2005
CategoriesControls, VB.NET
 
When you are navigating in the control, intercept the KeyPress event. If the key is Return, select the next cell that you want and set e.Handled = True to tell the control not to process the Return key.
 
' Ignore Return keys.
Private Sub DataGridView1_KeyDown(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.KeyEventArgs) Handles _
    DataGridView1.KeyDown
    If e.KeyCode = Keys.Return Then
        Dim cur_cell As DataGridViewCell = _
            DataGridView1.CurrentCell
        Dim col As Integer = cur_cell.ColumnIndex
        col = (col + 1) Mod DataGridView1.Columns.Count
        cur_cell = DataGridView1.CurrentRow.Cells(col)
        DataGridView1.CurrentCell = cur_cell

        e.Handled = True
    End If
End Sub
 
Unfortunately when you are editing a value, the DataGridView control doesn't have focus, the editing control (normally a DataGridViewTextBoxEditingControl--now that's a mouthful!) does so you cannot catch the Return key as easily. When you press Return, the editing control hides and focus moves to the next cell down.

To handle this, catch the EditingControlShowing event that occurs when the editing control is displayed and save the current row number. In the SelectionChanged event handler, restore the row if we were just editing.

 
' Save the current row number.
Private m_EditingRow As Integer = -1
Private Sub DataGridView1_EditingControlShowing(ByVal _
    sender As Object, ByVal e As _
    System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) _
    Handles DataGridView1.EditingControlShowing
    m_EditingRow = DataGridView1.CurrentRow.Index
End Sub

' If we just finished editing, restore the current row
' number.
Private Sub DataGridView1_SelectionChanged(ByVal sender As _
    Object, ByVal e As System.EventArgs) Handles _
    DataGridView1.SelectionChanged
    If m_EditingRow >= 0 Then
        Dim new_row As Integer = m_EditingRow
        m_EditingRow = -1
        DataGridView1.CurrentCell = _
            DataGridView1.Rows(new_row). _
                Cells(DataGridView1.CurrentCell.ColumnIndex)
    End If
End Sub
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated