Reputation: 23
I am trying to paste rows from an Excel sheet to a DataGridView
in C#.
I have used the following code:
private void PasteClipboard(DataGridView myDataGridView)
{
DataObject o = (DataObject)Clipboard.GetDataObject();
if (o.GetDataPresent(DataFormats.Text))
{
if (myDataGridView.RowCount > 0)
myDataGridView.Rows.Clear();
if (myDataGridView.ColumnCount > 0)
myDataGridView.Columns.Clear();
bool columnsAdded = false;
string[] pastedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");
foreach (string pastedRow in pastedRows)
{
string[] pastedRowCells = pastedRow.Split(new char[] { '\t' });
if (!columnsAdded)
{
for (int i = 0; i < pastedRowCells.Length; i++)
myDataGridView.Columns.Add("col" + i, pastedRowCells[i]);
columnsAdded = true;
continue;
}
myDataGridView.Rows.Add();
int myRowIndex = myDataGridView.Rows.Count - 1;
using (DataGridViewRow myDataGridViewRow = myDataGridView.Rows[myRowIndex])
{
for (int i = 0; i < pastedRowCells.Length; i++)
myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
}
}
However, as a result, only one row contains data while the others are empty. For instance, if I copy and paste 3 rows, the 3rd row is the only row with data and the other two rows are empty. What am I doing wrong?
Upvotes: 3
Views: 1814
Reputation: 3743
You need to do this:
int myRowIndex = myDataGridView.Rows.Add();
Instead of this:
myDataGridView.Rows.Add();
int myRowIndex = myDataGridView.Rows.Count - 1;
Note that when you create a new row, you also receive the index of that row, as the return value of myDataGridView.Rows.Add();
. Your code ignores that value and instead it assumes that the newly created row will always be the last one: myDataGridView.Rows.Count - 1;
Upvotes: 2