[英]How to move to another column in datagridview using Enter in vb.net
我已经搜索了这个,大多数答案都在C#中,并且我尝试将其转换为VB.NET并进行了变通,但是我找不到正确的代码。
我想要的是,当用户按下Enter键时,它将移至下一列,如果该行中的列是最后一列,那么它将向下移至第一列的第二行。
谢谢。
编辑:
If e.KeyCode = Keys.Enter Then
e.Handled = True
With dvJOBranch
Dim i As Integer = .CurrentCell.ColumnIndex + 1
.CurrentCell = .CurrentRow.Cells(i)
End With
End If
这段代码有效,但对于未编辑的列,如果我在列中进行编辑,则无法正常工作,这是错误的: 无法将当前单元格设置为不可见的单元格。
这应该可以解决问题
Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
Dim iCol = DataGridView1.CurrentCell.ColumnIndex
Dim iRow = DataGridView1.CurrentCell.RowIndex
If iCol = DataGridView1.Columns.Count - 1 Then
If iRow < DataGridView1.Rows.Count - 1 Then
DataGridView1.CurrentCell = DataGridView1(0, iRow + 1)
End If
Else
DataGridView1.CurrentCell = DataGridView1(iCol + 1, iRow)
End If
End If
End Sub
这将解决提到的“编辑”问题。
Private Sub DataGridView1_CellEndEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Dim iCol = DataGridView1.CurrentCell.ColumnIndex
Dim iRow = DataGridView1.CurrentCell.RowIndex
If iCol = DataGridView1.Columns.Count - 1 Then
If iRow < DataGridView1.Rows.Count - 1 Then
DataGridView1.CurrentCell = DataGridView1(0, iRow + 1)
End If
Else
If iRow < DataGridView1.Rows.Count - 1 Then
SendKeys.Send("{up}")
End If
DataGridView1.CurrentCell = DataGridView1(iCol + 1, iRow)
End If
End Sub
为了安全起见,您应该在单元格更改时获取“当前”列索引。然后您可以从该列开始增加..这也可以解决“编辑”问题
Public curcol, currow As Integer
Private Sub DataGridView2_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView2.CurrentCellChanged
Try
curcol = DataGridView2.CurrentCell.ColumnIndex
currow = DataGridView2.CurrentCell.RowIndex
Catch ex As Exception
curcol = 0
currow = 0
End Try
End Sub
Private Sub DataGridView2_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView2.KeyDown
Select Case e.KeyCode
Case Keys.Enter
DataGridView2.ClearSelection()
Try
If curcol = DataGridView1.Columns.Count - 1 Then
If currow < DataGridView2.Rows.Count - 1 Then
DataGridView2.CurrentCell = DataGridView2(0, currow + 1)
End If
Else
DataGridView2.CurrentCell = DataGridView2(curcol + 1, currow)
End If
Catch ex As Exception
Exit Try
End Try
End Select
End Sub
我认为 ....
Private Sub DataGridView1_EditingControlShowing(sender As System.Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
AddHandler e.Control.KeyDown, AddressOf cell_KeyDown
End Sub
Private Sub cell_KeyDown(sender As Object, e As KeyEventArgs)
If e.KeyCode = Keys.Enter Then
datagridview1.currentrow.cells(datagridview1.currentcelladress.x+1).selected=true
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.