Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy and paste multiple cells within DataGridView

Tags:

datagridview

I've seen that the Datagridview doesn't enable one to copy and paste the text of more than one cells, is there a simple setting to enable that or do I have to use the key handler and clipboard data store to include that functionality.

A user wants to copy 3 cells within a row and be able to paste the text of them in a different row.

like image 719
dimitarie Avatar asked Nov 02 '10 11:11

dimitarie


2 Answers

Ok, I got a solution but it hasn't been tested by pasting cells accross multiple rows.This is the KeyDown event of the datagridview

 if (e.Control && e.KeyCode == Keys.C)
            {
                DataObject d = AccountGrid.GetClipboardContent();
                Clipboard.SetDataObject(d);
                e.Handled = true;
            }
            else if (e.Control && e.KeyCode == Keys.V)
            {
                string s = Clipboard.GetText();
                string[] lines = s.Split('\n');
                int row = AccountGrid.CurrentCell.RowIndex;
                int col = AccountGrid.CurrentCell.ColumnIndex;
                string[] cells = lines[0].Split('\t');
                int cellsSelected = cells.Length;
                for (int i = 0; i < cellsSelected; i++)
                {
                    AccountGrid[col, row].Value = cells[i];
                    col++;
                }
            }
like image 118
dimitarie Avatar answered Oct 14 '22 04:10

dimitarie


        string s = Clipboard.GetText();
        string[] lines = s.Split('\n');
        int row = dataGridView1.CurrentCell.RowIndex;
        int col = dataGridView1.CurrentCell.ColumnIndex;
        foreach (string line in lines)
        {
            string[] cells = line.Split('\t');
            int cellsSelected = cells.Length;
            if (row < dataGridView1.Rows.Count)
            {
                for (int i = 0; i < cellsSelected; i++)
                {
                    if (col + i < dataGridView1.Columns.Count)
                        dataGridView1[col + i, row].Value = cells[i];
                    else
                        break;
                }
                row++;
            }
            else
            {
                break;
            }
        }
like image 1
user2484375 Avatar answered Oct 14 '22 05:10

user2484375