Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 452
Mark Lakata Avatar asked Nov 29 '22 13:11

Mark Lakata


2 Answers

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!

like image 64
Evan L Avatar answered Dec 05 '22 01:12

Evan L


In Visual Studio 2013's the winforms datagridview has various enumerations available for ClipboardCopyMode. To display header text, the user would use the "EnableAlwaysIncludeHeaderText" enumeration. Microsoft Reference

Disable

Copying to the Clipboard is disabled.

EnableAlwaysIncludeHeaderText

The text values of selected cells can be copied to the Clipboard. Header text is included for rows and columns that contain selected cells.

EnableWithAutoHeaderText

The text values of selected cells can be copied to the Clipboard. Row or column header text is included for rows or columns that contain selected cells only when the DataGridView.SelectionMode property is set to RowHeaderSelect or ColumnHeaderSelect and at least one header is selected.

EnableWithoutHeaderText

The text values of selected cells can be copied to the Clipboard. Header text is not included.

like image 34
WorkSmarter Avatar answered Dec 05 '22 03:12

WorkSmarter