Datagridview copy cell to clipboard

1
0

Hi!

Quick question (hopefully)

How do I copy the contents of a specific cell to clipboard when pressing ctrl-c ? I’ve tried the keypress event and also tried setting the ClipboardCopyMode to “ExludeUnselectedColumns”. Whatever I try I always copy the whole row with column headers regardless of the ClipboardCopyMode setting.

I also tried handling the KeyPress event and if the key was “c” then if My.Computer.Keyboard.CtrlKeyDown = True but this always returns false (My.Computer.Keyboard.CtrlShiftDown works though)

 

Can you help?

 

Thanks!

 

Vincent

  • You must to post comments
0
0

You can do this by using accelerators and the ClientClipboard extension.

Make sure to install the ClientClipboard extension using nuget.

To create an accelerator, open the Page in the designer and go the the Page properties. Click on the 3 dots by “Accelerators” and click “Add”. Click on the dropdown arrow and click the box for ctrl and set the key to C. See attached picture.

Once that’s set up, go to the lightning bolt to open the events for the page. Add an “Accelerator” event. It should be called Accelerator_CtrlC

Then paste this code in the accelerator event:

private async void Accelerator_CtrlC(object sender, AcceleratorEventArgs e)
{
if (dataGridView1.CurrentCell != null)
{
var value = dataGridView1.CurrentCell.Value?.ToString();
await ClientClipboard.WriteTextAsync(value);
}
}

I’ve attached a working sample here.

  • Julie(ITG)
    Note that instead of var value = dataGridView1.CurrentCell.Value?.ToString(); you can do string value = Convert.ToString(dataGridView1.CurrentCell.Value);
  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.