简体   繁体   中英

How can I paste multi-rows from Excel to a DataGridView in C#?

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM