简体   繁体   中英

How to send to clipboard datagridview content like CTRL-C

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.

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 , eg:

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 !

To simulate the effect of pressing ctrl c, you can use DataGridView.GetClipboardContent() . Eg:

Clipboard.SetText(this.dataGridView1.GetClipboardContent())

As described on MSDN:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM