How to copy "n" columns and "n" rows of excel to paste them into a datagridview with ClipBoard in C #?

0

My doubt arises since I try to paste the data of "n" columns and "n" rows. Since I'm trying with ClipBoard but it does not hit me the information I have in the clipboard.

private void PegarBtn_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var text = Clipboard.GetData(DataFormats.Text) as string;

            if (string.IsNullOrWhiteSpace(text))
                return;

            string[] lines = text.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.None);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Paste failed", MessageBoxButton.OK);
        }
    }
    
asked by Ab Hdez 09.11.2017 в 16:19
source

1 answer

0

You are missing the part where the "stuck" is done. I leave you the complete code that I found:

private void PasteClipboard()
{
    try
    {
        string s = Clipboard.GetText();
        string[] lines = s.Split('\n');
        int iFail = 0, iRow = dgData.CurrentCell.RowIndex;
        int iCol = dgData.CurrentCell.ColumnIndex;
        DataGridViewCell oCell;
        foreach (string line in lines)
        {
            if (iRow < dgData.RowCount && line.Length > 0)
            {
                string[] sCells = line.Split('\t');
                for (int i = 0; i < sCells.GetLength(0); ++i)
                {
                    if (iCol + i < this.dgData.ColumnCount)
                    {
                        oCell = dgData[iCol + i, iRow];
                        if (!oCell.ReadOnly)
                        {
                            if (oCell.Value.ToString() != sCells[i])
                            {
                                oCell.Value = Convert.ChangeType(sCells[i], 
                                                      oCell.ValueType);
                                oCell.Style.BackColor = Color.Tomato;
                            }
                            else
                                iFail++;
                                //only traps a fail if the data has changed 
                                //and you are pasting into a read only cell
                        }
                    }
                    else
                    { break; }
                }
                iRow++;
            }
            else
            { break; }
            if (iFail > 0)
                MessageBox.Show(string.Format("{0} updates failed due" + 
                                " to read only column setting", iFail));
        }
    }
    catch (FormatException )
    {
        MessageBox.Show("The data you pasted is in the wrong format for the cell");
        return;
    }
}
    
answered by 12.11.2017 / 03:23
source