这是我的工作代码,按Enter键移动到另一个单元格,如TAB:
Private Sub dvFromAlloc_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dvFromAlloc.KeyDown
If e.KeyCode = Keys.Enter Then
Dim colm As Integer = dvFromAlloc.ColumnCount - 1
Dim row As Integer = dvFromAlloc.RowCount - 1
Dim currCell As DataGridViewCell = dvFromAlloc.CurrentCell
If currCell.ColumnIndex = colm Then
If currCell.RowIndex < row Then
'gets the next row and the first selected index
dvFromAlloc.CurrentCell = dvFromAlloc.Item(0, currCell.RowIndex + 1)
End If
Else
'move in next col in the current row
dvFromAlloc.CurrentCell = dvFromAlloc.Item(currCell.ColumnIndex + 1, currCell.RowIndex)
End If
e.Handled = True
End If
End Sub
Private Sub dvFromAlloc_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dvFromAlloc.CellEndEdit
isEdited = True
iColumnindex = e.ColumnIndex
irowindex = e.RowIndex
End Sub
Private Sub dvFromAlloc_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dvFromAlloc.SelectionChanged
If isEdited Then
isEdited = False
dvFromAlloc.CurrentCell = dvFromAlloc.Item(iColumnindex + 1, irowindex)
End If
End Sub
这里的主要问题是,当我在最后一行时,我必须在编辑单元格之前按两次输入才能移动到另一个单元格,但如果我在其他行中,我只会按回车键编辑完单元格后,它将移动到下一个单元格。
感谢您的帮助
答案 0 :(得分:1)
这是我在CellandEdit和SelectionChanged中编辑的代码:
Private Sub dvFromAlloc_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dvFromAlloc.CellEndEdit
isEdited = True
iColumnindex = e.ColumnIndex
irowindex = e.RowIndex
If dvFromAlloc.CurrentRow.Index = dvFromAlloc.RowCount - 1 Then
If dvFromAlloc.CurrentCell.ColumnIndex < dvFromAlloc.ColumnCount - 1 Then
dvFromAlloc.CurrentCell = dvFromAlloc.Item(iColumnindex + 1, irowindex)
End If
isEdited = False
End If
End Sub
在上面的代码(CellEndEdit)中,我有一个第一个If语句:如果当前行索引等于行计数(这意味着我正在检查我是否在最后一行),那么我将执行第二个If言。
第二个If语句:如果当前列索引小于列数,则我将当前单元格移动到下一个单元格。
Private Sub dvFromAlloc_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dvFromAlloc.SelectionChanged
If isEdited Then
If dvFromAlloc.CurrentCell.ColumnIndex < dvFromAlloc.ColumnCount - 1 Then
dvFromAlloc.CurrentCell = dvFromAlloc.Item(iColumnindex + 1, irowindex)
Else
dvFromAlloc.CurrentCell = dvFromAlloc.Item(1, irowindex + 1)
End If
isEdited = False
End If
在上面的代码(SelectionChanged)中,我放了一个If else语句:如果当前单元格列索引小于列数,那么我将移动到下一个单元格,直到到达最后一列。 Elseif我在最后一列,然后我将当前单元格设置为列索引1并将行索引增加到1,以便它将移动到下一行。
我还将EditMode的DGV的属性更改为:EditonKeystrokeOrF2
这段代码非常适合我,我不会在keydown事件中更改代码。