Mark Lakata Mark Lakata - 4 years ago 190
C# Question

DataGridView select all cells and row headers and column headers for copy


of the
lets you select all the cells and row headers, or all the cell and column headers, but I can't figure out how to let the user select everything, including row headers and column headers at the same time.

I would like to give users the ability to copy and paste the whole table (including the column headers) into another document as text or formatted text, like Word or an email. It works great out of the box, except you can't get the column headers too.

Answer Source

The only way I've been able to achieve this is by creating a ToolStripMenuItem wtihin a ContextMenu control.

First I create a method that overrides the default ClipboardCopyMode for the DataGridView:

    public void CopyToClipboardWithHeaders(DataGridView _dgv)
        //Copy to clipboard
        _dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
        DataObject dataObj = _dgv.GetClipboardContent();
        if (dataObj != null)

Then I call that method and pass it the GridView in the click event of the ToolStripMenuItem:

    private void copyWithHeadersToolStripMenuItem_Click(Object sender, EventArgs e)

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download