VB.NET针对多个datagridviews的单击或键事件

时间:2017-10-25 11:10:36

标签: vb.net datagridview keyevent mouseclick-event

我有4个datagridviews,比方说Dgv1,Dgv2,Dgv3,Dgv4

假设我想使用向上和向下箭头键上下移动行。

有没有办法为所有datagridviews一次编码?

目前我必须像这样编码4次:

Private Sub Dgv1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Dgv1.KeyUp
    If e.KeyCode = Keys.Up OR e.KeyCode = Keys.Down OR e.KeyCode = Keys.PageUp Or e.KeyCode = Keys.PageDown Then
        Dim crRowIndex As Integer = Dgv1.CurrentCell.RowIndex
        Value = Dgv1.Rows(crRowIndex).Cells(4).Value.ToString
        ' Do more stuff
    End If
End Sub

这四次。所有datagridviews都从不同的sql表中获取不同的数据,但功能相同。虽然我在其他datagridviews中需要一个不同的单元格。

1 个答案:

答案 0 :(得分:1)

尝试将其更改为:

Private Sub Dgv1_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Dgv1.KeyUp, dgv2.keyup, dgv3.keyup, dgv4.keyup
If e.KeyCode = Keys.Up OR e.KeyCode = Keys.Down OR e.KeyCode = Keys.PageUp Or e.KeyCode = Keys.PageDown Then
    Dim dgv as DataGridView = DirectCast(sender, DataGridView)
    Dim crRowIndex As Integer = dgv.CurrentCell.RowIndex
    Value = dgv.Rows(crRowIndex).Cells(4).Value.ToString
    ' Do more stuff
End If
End Sub

基本上你只是添加到Handles列表,然后使用sender来获取正在处理的特定datagridview