Search code examples
c#.netwinformsdatagridview

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


The .SelectionMode of the DataGridView 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.


Solution

  • 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)
                Clipboard.SetDataObject(dataObj);
        }
    

    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)
        {
            CopyToClipboardWithHeaders(dgv);
        }
    

    Hope that helps!