誰かが私を助けてくれないかと思っていました。クリップボードから DatagridView にコピーするコードをいくつか書きました。私が抱えている問題は、最初のセルを除いて、すべてが想定どおりに機能することです。
たとえば、Excel の 2 列から 1 行のみをコピーすると、最初の列に 20 の値、2 番目の列に 30 の値がコピーされます。
次に、DataGridView に貼り付けると、次のようになります。
最初の列では数値 20 を取得し、次に大きなスペースと 30 の値を取得しますが、2 番目の列では 30 の値のみが表示されます。
以下は私のコードIDです。誰かがその最初のセルを修正する方法についてアイデアを持っています。助けてください
if (e.Control && e.KeyCode == Keys.V)
{
char[] rowSplitter = { '\r', '\n' };
char[] columnSplitter = { '\t' };
//get the text from clipboard
IDataObject dataInClipboard = Clipboard.GetDataObject();
string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text);
//split it into lines
string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
//get the row and column of selected cell in grid
int r = DGV.SelectedCells[0].RowIndex;
int c = DGV.SelectedCells[0].ColumnIndex;
//add rows into grid to fit clipboard lines
if (DGV.Rows.Count < (r + rowsInClipboard.Length))
{
MessageBox.Show("PasteValues Will be Outside of Grid");
return;
}
// loop through the lines, split them into cells and place the values in the corresponding cell.
for (int iRow = 0; iRow < rowsInClipboard.Length; iRow++)
{
//split row into cell values
string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);
//cycle through cell values
for (int iCol = 0; iCol < valuesInRow.Length; iCol++)
{
//assign cell value, only if it within columns of the grid
if (DGV.ColumnCount - 1 >= c + iCol)
{
DGV.Rows[r + iRow].Cells[c + iCol].Value = valuesInRow[iCol];
for (int i = 0;
i < selectedCellCount; i++)
{
DGV.SelectedCells[i].Value = valuesInRow[iCol]; ;
}
}
}
}
}