peter
peter

Reputation: 2103

How can I modify what gets copied to the Clipboard?

I'm copying a DataGrid to the clipboard so that it can be pasted to e.g. Excel while maintaining its format like this:

MyDataGrid.SelectAllCells();
MyDataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, MyDataGrid);

This works very nice. However, I need to add the string "MyDataGridTitle". If pasted to Excel, this should simply stand above the DataGrid.

I have tried various ways (e.g. use a DataObject) and tortured google, but to no success. I'd be thankful for a hint, tip or answer!

Upvotes: 1

Views: 914

Answers (1)

Il Vic
Il Vic

Reputation: 5666

This is not a very elegant solution, but you can try by manipulating the html string generated by your DataGrid (indeed when you paste in Excel, the DataFormats.Html format is the one which is used).

Something like this:

dg.SelectAllCells();
dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dg);

string dataGridContent = (string)Clipboard.GetData(DataFormats.Html);
dataGridContent = dataGridContent.Replace("<TABLE>",
    String.Format("<TABLE><TR><TD colspan='{0}'>Your additional text<TD></TR>", dg.Columns.Count));

Clipboard.SetText(dataGridContent, TextDataFormat.Html);

Of course you can improve this code for example by using regular expressions instead of the Replace method.

Upvotes: 1

Related Questions