如何在VB.net中的datagridview单元格结束编辑中捕获箭头键

时间:2013-10-25 05:25:30

标签: vb.net datagridview cell arrow-keys

以下是我的Cell End Edit和Selection Changed事件的代码:

Private Sub dvJOBranch_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dvJOBranch.CellEndEdit

    'get the current column and row index
    curCol = e.ColumnIndex
    curRow = e.RowIndex

    'if the cell is blank, set it to zero
    If IsDBNull(dvJOBranch.Rows(curRow).Cells.Item(curCol).Value) Then
        dvJOBranch.Rows(curRow).Cells.Item(curCol).Value = 0

        'convert it to integer
    Else
        dvJOBranch.Rows(curRow).Cells.Item(curCol).Value = _
            Convert.ToInt32(dvJOBranch.Rows(curRow).Cells.Item(curCol).Value.ToString())
    End If



    'if the user do mouseclick in datagridview
    isMouseClick = dvJOBranch.Capture.ToString()

    'if the user does not click any cell from the datagridview
    If isMouseClick = False Then

        isEdited = True
        iColumnindex = e.ColumnIndex
        irowindex = e.RowIndex

        If dvJOBranch.CurrentRow.Index = dvJOBranch.RowCount - 1 Then
            If dvJOBranch.CurrentCell.ColumnIndex < dvJOBranch.ColumnCount - 1 Then
                dvJOBranch.CurrentCell = dvJOBranch.Item(iColumnindex + 1, irowindex)
            End If
            isEdited = False
        End If

    End If



End Sub

Private Sub dvJOBranch_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dvJOBranch.SelectionChanged

    'if the user does not click any cell from the datagridview
    If isMouseClick = False Then

        If isEdited Then
            If dvJOBranch.CurrentCell.ColumnIndex < dvJOBranch.ColumnCount - 1 Then
                dvJOBranch.CurrentCell = dvJOBranch.Item(iColumnindex + 1, irowindex)
            Else
                dvJOBranch.CurrentCell = dvJOBranch.Item(2, irowindex + 1)
            End If
            isEdited = False
        End If


    End If

    'set it to false
    isMouseClick = False

End Sub

此代码的功能是在使用ENTER键编辑后将当前单元格移动到右侧。在我的代码中,如果用户单击任何单元格,我也会捕获鼠标单击,因为它有错误如果我没有捕获鼠标单击,我现在要做的是在编辑时捕捉箭头键。因为在编辑单元格之后,例如当我按下箭头键向上时,它会像我的ENTER键的函数一样向右移动,而不是向上移动。

任何帮助和指导将不胜感激,谢谢

1 个答案:

答案 0 :(得分:2)

您可能正在使用datagridview的KeyUp事件,如下所示:

Private Sub dvJOBranch(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dvJOBranch.KeyUp
    If e.KeyCode = Keys.Up Then
        ' Do your code here
    End If
End Sub

如果你想在那里处理回车键,你也可以使用一个选择案例:

 Private Sub dvJOBranch(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dvJOBranch.KeyUp
    Select Case e.KeyCode
        Case Keys.Enter
            ' Code for enter
        Case Keys.Up
            ' Code for up arrow
            'Etc
    End Select
End Sub