Pasting excel data into a blank DataGridView - Index out of range exception

前端 未结 8 1451
不思量自难忘°
不思量自难忘° 2020-12-30 07:20

I have an excel sheet with the following:

\"enter

So, what I am trying to achi

8条回答
  •  时光说笑
    2020-12-30 08:05

    After some digging around, I found that I have to add columns first, then add a new row, get the row index of the newly created row, and then set the cell values.

    Here's the updated code:

    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];
            }
        }
    }
    

    }

    And here it is working:

    enter image description here

    Happy to accept criticisms and useful tips on improving this. This code is quite slow...

提交回复
热议问题