将DataGridViewSelectedCellCollection复制并粘贴到剪贴板
假设我有一个DataGridView
,它由Cells中的许多不同的strings
(不同的长度,数字和纯文本)填充。
我想要做的是复制和粘贴这些字符串,这可能是任何选择的单元格。
我的复制方法是:
if (e.Control && e.KeyCode == Keys.C)
{
// copy
DataGridViewSelectedCellCollection tmpCells = this.MyDataGridView.SelectedCells;
Clipboard.SetDataObject(tmpCells);
}
哪个工作正常。
我的粘贴方法是:
if (e.Control && e.KeyCode == Keys.V)
{
// paste
IDataObject dataInClipboard = Clipboard.GetDataObject();
string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text);
char[] rowSplitter = { 'r', 'n' };
char[] columnSplitter = { 't' };
string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
int r1 = this.MyDataGridView.SelectedCells[0].RowIndex;
int c1 = this.MyDataGridView.SelectedCells[0].ColumnIndex;
int r2 = this.MyDataGridView.SelectedCells[this.MyDataGridView.SelectedCells.Count-1].RowIndex;
int c2 = this.MyDataGridView.SelectedCells[this.MyDataGridView.SelectedCells.Count-1].ColumnIndex;
int r = Math.Min(r1, r2); // Do not care if selection was taken by drag mouse up or down, always start from min
int c = Math.Min(c1, c2); // Do not care if selection was taken by drag mouse left or right, always start from min
for (int iRow = 0; iRow < rowsInClipboard.Length; ++iRow )
{
string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);
for (int iCol = 0; iCol < valuesInRow.Length; ++iCol )
{
if (this.MyDataGridView.ColumnCount-1 >= c + iCol)
{
DataGridViewCell DGVC = (this.MyDataGridView.Rows[r + iRow].Cells[c + iCol]);
DGVC.Value = valuesInRow[iCol];
}
}
}
}
}
哪些工作正常, 除非字符串本身不包含我用rowSplitter
和columnSplitter
指定的任何分隔符。 但不幸的是,这种情况经常发生。 然后它将字符串分开并将其展开到下一个单元格。
例:
Cell[n] = {"This string contains a new line delimiter n but should use only one cell."}
将被粘贴到:
Cell[n] = {"This string contains a new line delimiter"};
Cell[n+1] = {"but should use only one cell."}
所以我的问题是:是否有可能恢复DataGridViewSelectedCellCollection
之前它被复制到剪贴板? 只需将object
为DataGridViewSelectedCellCollection
将不起作用:
DataGridViewSelectedCellCollection DGSCC = (DataGridViewSelectedCellCollection)dataInClipboard; // compiles, but throws exception at runtime
我有任何其他选项,但通过定义的格式解析每个字符串?
你将不得不为剪贴板定义自己的格式,这将做默认的不能为你做的。
在这种特定情况下最简单的解决方案是将多行分隔符转换为n
,然后在粘贴时转换回来,但无论如何它意味着不再需要
DataGridViewSelectedCellCollection tmpCells = this.MyDataGridView.SelectedCells;
Clipboard.SetDataObject(tmpCells);
但
DataGridViewSelectedCellCollection tmpCells = this.MyDataGridView.SelectedCells;
string result = "";
foreach(DataGridViewCell cell in tempCells)
// ... try to replicate what default clipboard text representation does
// change line breaks
Clipboard.SetDataObject(result.Replace("xdxa", "n"));
并粘贴将是:
IDataObject dataInClipboard = Clipboard.GetDataObject();
string stringInClipboard = dataInClipboard.GetData(DataFormats.Text).ToString().Replace("n", "xdxa");
链接地址: http://www.djcxy.com/p/62263.html
上一篇: Copy+Paste DataGridViewSelectedCellCollection to/from Clipboard