views:

438

answers:

2

Hi,

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..

+1  A: 

See How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms DataGridView Control

Stuart Dunkeld
I tried this solution. But it doesn't seem to be working.
nav100
Didn't work how? Error? No data on clipboard?
Stuart Dunkeld
A: 

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);
                        }

                    }
                }
     }
}
0A0D
What is wrong with this code? private DataObject OnCopySelectedRowsToClipboard() { this.MyDataGridView.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; // Add the selection to the clipboard. Clipboard.SetDataObject( this.MyDataGridView.GetClipboardContent()); return new DataObject(Clipboard.GetText()); }
nav100
Nothing except I'm not sure why you are doing return new DataObject(Clipboard.GetText()); but it should have no effect that I can see
0A0D