我的表单上有一个包含两列的Datagridview。我只想要选择第一列中的单元格。所以我使用datagridview的keydown事件来捕获TAB和SHIFT + TAB。因此,如果选择第一行并且用户按Tab键,则将选择第二行而不是停留在第一行并选择第二列的单元格。
我对TAB键的if语句工作正常,但由于某种原因,SHIFT + TAB语句不正常。当前所选单元格上方的单元格未被选中。没有任何事情发生。
Private Sub myGrid_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles myGrid.KeyDown
If e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
SendKeys.Send("{DOWN}")
End If
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
SendKeys.Send("{UP}")
End If
End Sub
真的很奇怪的是,如果我在它工作的语句中添加一个消息框。
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
MsgBox("test")
e.SuppressKeyPress = True
SendKeys.Send("{UP}")
End If
有什么想法吗?
答案 0 :(得分:0)
Sendkeys是最后的,不得已的......
这样的事情怎么样:
Private Sub dgv_KeyDown(sender As Object, e As KeyEventArgs) Handles dgv.KeyDown
If e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
dgv.CurrentCell = dgv(0, dgv.CurrentCell.RowIndex + 1)
End If
End Sub
答案 1 :(得分:0)
在@rheitzman的帮助下,我能够看到主要问题。问题来自于在两个不同的if语句中使用TAB和SHIFT + TAB。这是我更新的代码:
Private Sub myGrid_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles myGrid.KeyDown
Dim row As String = Me.myGrid.CurrentCellAddress.Y
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
Me.myGrid.CurrentCell = Me.myGrid.Rows(row - 1).Cells(0)
Me.myGrid.Rows(row - 1).Cells(0).Selected = True
ElseIf e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
Me.myGrid.CurrentCell = Me.myGrid.Rows(row + 1).Cells(0)
Me.myGrid.Rows(row + 1).Cells(0).Selected = True
End If
End Sub
答案 2 :(得分:0)
Tab和Shift + Tab已由Windows Forms和DataGridView处理。他们移动单元格荧光笔/选择器向左(上一个)和右(下一个)移动。您必须创建一个继承DataGridView并手动覆盖其功能以实现所需功能的类,然后将该新类用于数据网格。
答案 3 :(得分:0)
Private Sub DataGridView1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
Dim r As Integer = Me.DataGridView1.CurrentCellAddress.Y
Dim f As Integer = Me.DataGridView1.CurrentCellAddress.X
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
If 0 = r Then
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(f - 1)
Me.DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(f - 1).Selected = True
Else
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(r - 1).Cells(f)
Me.DataGridView1.Rows(r - 1).Cells(f).Selected = True
End If
ElseIf e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
If DataGridView1.RowCount = (r + 1) Then
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(0).Cells(f + 1)
Me.DataGridView1.Rows(0).Cells(f + 1).Selected = True
Else
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(r + 1).Cells(f)
Me.DataGridView1.Rows(r + 1).Cells(f).Selected = True
End If
End If
End Sub