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

前端 未结 8 1523
不思量自难忘°
不思量自难忘° 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 07:53

    Perfect Code here: (write in button)

    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");
        int j=0;
        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[j])
            {
                for (int i = 0; i < pastedRowCells.Length; i++)
                    myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
            }
            j++;
        }
    }
    

    Modified from Latheesan's code.

提交回复
热议问题