使用enter键在datagridview单元格中导航

时间:2014-09-28 16:53:02

标签: vb.net datagridview enter

我尝试了几种组合,但没有取得任何成功。当按下按钮时,焦点位于黄色(1),我想当按下回车键时,该焦点转到单元格(2),然后是(3),依此类推。

enter image description here

如果没有单元格编辑,只需输入密钥就可以使用以下代码:

 Private Sub DGVBU1_KeyDown(sender As Object, e As KeyEventArgs) Handles DGVBU1.KeyDown
        If e.KeyCode = Keys.Enter Then
            Dim CLIndex As Integer = DGVBU1.CurrentCell.ColumnIndex
            Dim RWIndex As Integer = DGVBU1.CurrentCell.RowIndex
            If CLIndex = 2 Then
                DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex - 1).Cells(CLIndex + 1)
            ElseIf CLIndex = 3 Then
                DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex).Cells(CLIndex - 1)
            End If
        End If
    End Sub

但是当在单元格编辑后按下Enter键时,它会向下移动到行+ 1。

我也试过这个:

Private Sub DGVBU1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DGVBU1.CellEndEdit
    Dim CLIndex As Integer = DGVBU1.CurrentCell.ColumnIndex
    Dim RWIndex As Integer = DGVBU1.CurrentCell.RowIndex
    If CLIndex = 2 Then
        DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex).Cells(CLIndex - 1)
        DGVBU1.CurrentCell = DGVBU1.Rows(8).Cells(CLIndex + 1)
    ElseIf CLIndex = 3 Then
        DGVBU1.CurrentCell = DGVBU1.Rows(RWIndex).Cells(CLIndex - 1)
    End If
End Sub

...但是然后输入密钥从(1)直接发送焦点到单元格(4)。

是否可以使这项工作?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

如果DataGridView可能正在拦截keydown事件中的Enter键。如果这是问题,解决方案是派生控件类并重写ProcessCmdKey:

受保护的覆盖函数ProcessCmdKey(ByRef msg As Message,ByVal keydata As Keys)As Boolean

如果keydata = Keys.Enter然后   OnKeyDown(New KeyEventArgs(keydata))   ProcessCmdKey = True 其他   ProcessCmdKey = MyBase.ProcessCmdKey(msg,keydata)   结束如果

结束功能

答案 1 :(得分:0)

Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
    If e.KeyCode = Keys.Enter Then
       Select Case DataGridView1.CurrentCell.ColumnIndex
            Case 0
                e.Handled = True
                DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(DataGridView1.CurrentCell.ColumnIndex + 1).Selected = True
            Case 1
                e.Handled = True
                Try
                    DataGridView1.Rows(DataGridView1.CurrentRow.Index + 1).Cells(2).Selected = True
                Catch ex As Exception
                End Try
       End Select
    End If
End Sub