2
假设我有一个DataGridView
,它由单元格中的许多不同的strings
(不同的长度,数字和纯文本)填充。将DataGridViewSelectedCellCollection复制并粘贴到剪贴板
我想要做的是复制和粘贴这些字符串,这可能是任何选择的单元格。
我的方法副本是:
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];
}
}
}
}
}
工作正常除非字符串本身DOES NOT包含我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
我必须通过定义的格式的任何其他选择,只能解析每个字符串?
好主意,容易实现! – fiscblog