Copy and paste in different formats

c#

Solution

If you look at the clipboard class you can set the text but there is also quite a bit more you can do with it. Most of the advanced things you will want to do with the clipboard revolve around a pair of routines "SetDataObject" and "GetDataObject". To use this with multiple formats you can specify:

var serializableObject = new MyObject();

var clipData = new DataObject();
clipData.SetData(DataFormats.Text, "abcdefg");
clipData.SetData("CustomFormat", serializableObject);
Clipboard.SetDataObject(data);

Once you have done this you can get the data back from the clipboard by reversing this and requesting the data from the custom format. Briefly the reverse call looks like:

var clipData = (DataObject)Clipboard.GetDataObject();
var myObject = clipData.GetData("CustomFormat") as MyObject;

For a more complete example from Microsoft, see this page: http://msdn.microsoft.com/en-us/library/637ys738(v=vs.110).aspx. Just look at the bottom where it explains the use of multiple formats.

Hope this helps. Best of luck!

Problem

I have a datagrid that I want to be able to copy and paste to/from excel. Pretty common scenario. I have the copy and paste functions implemented. However, this application has several datagrids, and I'd like to prevent the user from trying to copy data from one grid to another since the data is different. I can serialize the objects in these grids to any format I want, so adding some kind of metadata that says "This data only goes in that grid" is trivial. But I can't add the metadata because then it would show up in excel. Is there some solution to this problem that allows me to paste data in one format in my application, but that excel will still handle correctly?

Original source