Reputation: 6477
How to send to clipboard selected content from DataGridView, simulating CTRL-C behavior.
This isn't working as expected:
Clipboard.SetText(this.dataGridView1.SelectedCells.ToString());
User needs to paste in Excel. CTRL-C is working fine, but I need to script for context menu.
Upvotes: 2
Views: 3009
Reputation: 14021
To simulate the effect of pressing ctrl c, you can use DataGridView.GetClipboardContent()
. Eg:
Clipboard.SetText(this.dataGridView1.GetClipboardContent())
This method retrieves data that represents the region defined by the selected cells. This region is the smallest rectangle that includes all of the selected cells.
The value for each selected cell in this region is retrieved by calling the DataGridViewCell.GetClipboardContent
method. Blank placeholder values are used for unselected cells in this region. This method combines these values into a DataObject containing several formats for copying to the clipboard.
The supported clipboard formats include DataFormats.Text, DataFormats.UnicodeText, DataFormats.Html, and DataFormats.CommaSeparatedValue.
Upvotes: 0
Reputation: 54433
SelectedCells
is a CellCollection
and as such has no useful ToString method.
If you want to copy just one cell you have to decide which and then copy its Value
, e.g.:
Clipboard.SetText(this.dataGridView1.SelectedCells[0].Value.ToString());
If you want to copy a range of cells things get more complicated, especially if the cell range is not contiguous.. But Crtl-C will also not work over a cell range going DGV -> clipboard -> Excel.
For a simple range, if you need it, you should be able to construct the necessary string by concatenating the cells values with TABs
to move a cell to the right and CRLF
to go to the next row.. Will you need that?
Note: Before trying to access SelectedCells[0]
you need to check if SelectedCells.Count > 0
!
Upvotes: 1