Search code examples
c#.netdatagridinsertclipboard

.NET DataGrid Copy/Paste


I have a datagrid in C# Project. What I am trying to do is copy data from datagrid and then paste in file. Then edit content and insert back to datagrid from clipboard.

I can copy data from datagrid into clipboard but I can not insert/replace text from clipboard into datagrid.

How can I insert data from clipboard into datagrid?

Sample data copied from datagrid and pasted into the file:

>  0 base_hair00 Egyptian 0 2 2 2 2 1 _S_Hair000_Front_L _C_elf-f-hair000 0 Hair000_Bottom_S _C_elf-f-hair000 0 Hair000_Top_S _C_elf-f-hair000 0 - - 0 - - 0 - -

This I am trying to insert into datagrid at the end

>  0 base_hair02 Egyptian2 0 2 2 2 2 1 _S_Hair000_Front_L _C_elf-f-hair000 0 Hair000_Bottom_S _C_elf-f-hair000 0 Hair000_Top_S _C_elf-f-hair000 0 - - 0 - - 0 - -

Solution

  • Add a "Paste" function or handle the KeyDown event to listen for a Paste action like this:

        void datagrid_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == System.Windows.Forms.Keys.V && e.Control)
            {
                string data = Clipboard.GetData(DataFormats.Text).ToString();
                string[] cells = data.Split('\t');
                for (int i = 0; i < cells.Length; i++)
                    datagrid[datagrid.CurrentRowIndex, i] = cells[i];
            }
        }