nav100
nav100

Reputation: 51

Copy Datagridview to clipboard in Windows Forms

I would like to copy Datagridview selected rows to clipboard and paste them in notepad or Microsoft Word. What is the best method to achieve this?

Thank you..

Upvotes: 0

Views: 5656

Answers (3)

mcNux
mcNux

Reputation: 1501

This will copy the currently selected cells in the DataGridView called myDataGridView data to the clipboard.

Clipboard.SetDataObject(myDataGridView.GetClipboardContent())

Upvotes: 1

user195488
user195488

Reputation:

I use a Copy menu item. If you want to use Ctrl+C, then you'll have to implement keyboard events. Here is my code:

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
       foreach (Control myControl in tabControl1.SelectedTab.Controls)
       {
             if (myControl is DataGridView))
             {
                    DataGridView tempdgv = (DataGridView)myControl;
                    DataObject dataObj = tempdgv.GetClipboardContent();
                    try
                    {
                        Clipboard.SetDataObject(dataObj, true);
                    }
                    catch (Exception ex)
                    {
                         // Do Something
                    }
                    finally
                    {
                        if (selectAllToolStripMenuItem.Checked)
                        {
                            selectAllToolStripMenuItem_Click(this, EventArgs.Empty);
                        }

                    }
                }
     }
}

Upvotes: 4

Related Questions