在DataGridView中模拟标题单击

时间:2012-06-07 11:26:02

标签: vb.net

我正在尝试使用快捷键模拟datagridview第1列中的headerclick,但我不知道如何。

Private Sub frm_lista_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles Me.KeyDown
  If e.KeyCode = Keys.S And e.Alt Then
    'this handler exists  
    DataGridView1_ColumnHeaderMouseClick(whathere, whathere)
  End If
End Sub

有任何帮助吗?

1 个答案:

答案 0 :(得分:4)

确保表单已设置此属性:

Me.KeyPreview = True

由于您尝试从键盘事件指定第1列,因此您可以传递自己的事件参数:

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
  If ((Control.ModifierKeys And e.Alt) AndAlso e.KeyCode = Keys.S) Then
    Dim mea As New MouseEventArgs(MouseButtons.None, -1, -1, -1, -1)
    Dim dgvcme As New DataGridViewCellMouseEventArgs(1, -1, -1, -1, mea)
    DataGridView1_ColumnHeaderMouseClick(DataGridView1, dgvcme)
  End If
End Sub

该事件现在应该设置e.ColumnIndex属性。

Private Sub DataGridView1_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick
  If e.ColumnIndex = 1 Then
    MessageBox.Show("OK")
  End If
End Sub

或者,您可以从两个地方调用子例程:

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
  If ((Control.ModifierKeys And e.Alt) AndAlso e.KeyCode = Keys.S) Then
    Call HandelColumnOneClick()
  End If
End Sub

Private Sub DataGridView1_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick
  If e.ColumnIndex = 1 Then
    Call HandleColumnOneClick()
  End If
End Sub

Private Sub HandleColumnOneClick()
  '// Do Something
End Sub