Reputation: 7279
I am attempting to do a really simple copy and paste inside of a DataGridView cell using Ctrl+C and CTRL+ V.
I don't need to be able to copy or paste multiple cells, just the selected text of a single selected cell.
Edit mode for the DataGridView is set to EditOnEnter because they didn't like having to double click to edit the value.
Neither CTRL+C nor CTRL+V work normally inside the cell.
I found a workaround, but it's really buggy:
Private Sub dgParts_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgParts.EditingControlShowing
AddHandler e.Control.KeyUp, AddressOf dgParts_TextBox_KeyUp
End Sub
Private Sub dgParts_TextBox_KeyUp(sender As Object, e As KeyEventArgs)
If e.KeyCode = Keys.C AndAlso e.Modifiers = Keys.Control Then
Clipboard.SetText(sender.SelectedText)
End If
If e.KeyCode = Keys.V AndAlso e.Modifiers = Keys.Control Then
sender.SelectedText = Clipboard.GetText
End If
End Sub
For some reason KeyUp triggers multiple times, so when I do a paste it inserts the text 5 times.
I tried switching it over to a KeyDown instead of KeyUp, but then it triggers when I hit CTRL, and not when I also hit C or V.
It really doesn't seem like it should be this hard to do something so simple, so I'm hoping that I'm just missing something that will make it just work.
Upvotes: 0
Views: 250
Reputation: 3271
Whenever you add an Event Handler in code using syntax like
AddHandler e.Control.KeyUp, AddressOf dgParts_TextBox_KeyUp
It is good practice to precede that line of code with its opposite, to remove any previously added Event Handlers. If you don't then you are likely to encounter the situation you are facing with the same event being handled multiple times.
Change the Sub dgParts_EditingControlShowing
to contain RemoveHandler e.Control.KeyUp, AddressOf dgParts_TextBox_KeyUp
Final version should be like:
Private Sub NewMethod(sender As Object, e As DataGridViewEditingControlShowingEventArgs)
RemoveHandler e.Control.KeyUp, AddressOf dgParts_TextBox_KeyUp
AddHandler e.Control.KeyUp, AddressOf dgParts_TextBox_KeyUp
End Sub
Upvotes: 1