DataGridView:复制完成到剪贴板 [英] DataGridView: Copy complete to clipboard
问题描述
我在 .Net 应用程序 (V4 C# VS2010) 中有一个 DataGridView &想要通过单击按钮将所有数据复制到剪贴板.没问题-
I have a DataGridView in a .Net application (V4 C# VS2010) & want to copy all the data to the clipboard on the click of a button. No problem -
private void copyToClipboard()
{
dataGridView1.SelectAll();
DataObject dataObj = dataGridView1.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
问题是用户可能已经在 DataGrid & 上选择了一些单元格、行等.我真的不想改变那个选择.以上显然选择了一切.我可以 dataGridView1.ClearSelection();最后稍微好一点,但仍然没有达到要求.
Problem is that the user might already have some cells, rows etc selected on the DataGrid & I don't really want to change that selection. The above obviously selects everything. I could dataGridView1.ClearSelection(); at the end which is marginally better but still doesn't achieve what's required.
我可以保存选定的单元格:
I can save the selected cells:
var mySelectedCells = dataGridView1.SelectedCells;
但是如何在复制后在 DataGrid 上重新选择那些选定的单元格?有没有一种简单的方法可以将选定的单元格集合返回到 DataGrid 中?也许有更好的方法首先将整个网格复制到剪贴板而不影响当前选定的单元格?
but how do I get those selected cells reselected on the DataGrid after the copy? Is there an easy way to get the selected cells collection back into the DataGrid? Perhaps there is a better way to get the whole grid copied to the clipboard in the first place without affecting presently selected cells?
推荐答案
我想如果您只想将单元格的内容表示为文本并将它们复制到剪贴板,以制表符分隔,您可以执行以下操作:
I suppose if you just wanted to represent the contents of the cells as text and copy them to the clipboard, tab-delimited, you could do something like:
var newline = System.Environment.NewLine;
var tab = " ";
var clipboard_string = "";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i=0; i < row.Cells.Count; i++)
{
if(i == (row.Cells.Count - 1))
clipboard_string += row.Cells[i].Value + newline;
else
clipboard_string += row.Cells[i].Value + tab;
}
}
Clipboard.SetText(clipboard_string);
输出看起来与 GetClipboardContent()
的输出非常相似,但要注意任何 DataGridViewImageColumns 或任何不是隐式字符串的类型.
The output seems pretty similar to that of the GetClipboardContent()
, but be careful for any DataGridViewImageColumns or any type that isn't implicitly a string.
Anthony 是正确的,使用 StringBuilder 避免为每个连接分配一个新字符串.新代码:
Anthony is correct, use StringBuilder to avoid allocating a new string for every concatenation. The new code:
var newline = System.Environment.NewLine;
var tab = " ";
var clipboard_string = new StringBuilder();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (i == (row.Cells.Count - 1))
clipboard_string.Append(row.Cells[i].Value + newline);
else
clipboard_string.Append(row.Cells[i].Value + tab);
}
}
Clipboard.SetText(clipboard_string.ToString());
这篇关于DataGridView:复制完成到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!