简体   繁体   中英

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

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

                    }
                }
     }
}

这会将DataGridView中当前选定的单元格myDataGridView数据复制到剪贴板。

Clipboard.SetDataObject(myDataGridView.GetClipboardContent())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM