Reputation: 175
I have 4 datagridviews, let's say Dgv1, Dgv2, Dgv3, Dgv4
Suppose I want to move up and down the rows with the up and down arrow key.
Is there a way to code this one time for all datagridviews?
At the moment I have to code it 4 times like this:
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
And this four times. All datagridviews get different data from different sql tables but the functionality is the same. Although I need a different cell in other datagridviews.
Upvotes: 0
Views: 236
Reputation: 114
Try changing it to this:
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
Basically you are just adding to the Handles list and then using sender to get the specific datagridview that is being handled
Upvotes: 1