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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With