I am trying to add a paste function to my Windows Forms DataGridView in C#. I already have some code that works just fine, but only as long as the DataGridView has "enough" columns and lines.
Let's say I have copied one Excel column with five lines and I want to paste it to a column in DataGridView with four lines, the last line gets cut off. My aim is that this line is supposed to be added, so that the pasted value can be added as well.
This is my code:
string s = Clipboard.GetText();
string[] lines = s.Split('\n');
int row = dataGridView1.CurrentCell.RowIndex;
int col = dataGridView1.CurrentCell.ColumnIndex;
foreach (string line in lines)
{
if (row < dataGridView1.RowCount && line.Length >0)
{
string[] cells = line.Split('\t');
for (int i = 0; i < cells.GetLength(0); ++i)
{
if (col + i < this.dataGridView1.ColumnCount)
{
dataGridView1[col + i, row].Value = Convert.ChangeType(cells[i], dataGridView1[col + i, row].ValueType);
}
else
{
break;
}
}
row++;
}
else
{
break;
}
}