[英]How to send to clipboard datagridview content like CTRL-C
How to send to clipboard selected content from DataGridView, simulating CTRL-C behavior. 如何从DataGridView发送选定的内容到剪贴板,以模拟CTRL-C行为。
This isn't working as expected: 这无法正常工作:
Clipboard.SetText(this.dataGridView1.SelectedCells.ToString());
User needs to paste in Excel. 用户需要粘贴到Excel中。 CTRL-C is working fine, but I need to script for context menu. CTRL-C正常工作,但是我需要为上下文菜单编写脚本。
SelectedCells
is a CellCollection
and as such has no useful ToString method. SelectedCells
是一个CellCollection
,因此没有有用的ToString方法。
If you want to copy just one cell you have to decide which and then copy its Value
, eg: 如果只想复制一个单元格,则必须决定哪个单元格,然后复制其Value
,例如:
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. 如果要复制一定范围的单元格,事情会变得更加复杂,尤其是在单元格范围不连续的情况下。但是Crtl-C在DGV->剪贴板-> 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? 对于简单范围 ,如果需要,您应该能够通过将单元格值与TABs
串联以将单元格移至右侧,并将CRLF
移至下一行来构造必要的字符串。是否需要?
Note : Before trying to access SelectedCells[0]
you need to check if SelectedCells.Count > 0
! 注意 :在尝试访问SelectedCells[0]
您需要检查SelectedCells.Count > 0
!
To simulate the effect of pressing ctrl c, you can use DataGridView.GetClipboardContent()
. 要模拟按ctrl c的效果,可以使用DataGridView.GetClipboardContent()
。 Eg: 例如:
Clipboard.SetText(this.dataGridView1.GetClipboardContent())
As described on MSDN: 如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. 通过调用DataGridViewCell.GetClipboardContent
方法,可以检索此区域中每个选定单元格的值。 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. 此方法将这些值组合到一个DataObject中,该DataObject包含几种格式以复制到剪贴板。
The supported clipboard formats include DataFormats.Text, DataFormats.UnicodeText, DataFormats.Html, and DataFormats.CommaSeparatedValue. 支持的剪贴板格式包括DataFormats.Text,DataFormats.UnicodeText,DataFormats.Html和DataFormats.CommaSeparatedValue。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.