I am trying to copy an object onto the windows clipboard and off again. My code is like this:
Copy on to clipboard:
Clipboard.Clear();
DataObject newObject = new DataObject(prompts);
newObject.SetData(myString);
Clipboard.SetDataObject(newObject);
Where prompts
is a List<Data.Sources.PromptResult>
collection.
Copy off clipboard:
IDataObject dataObject = System.Windows.Forms.Clipboard.GetDataObject();
if (dataObject.GetDataPresent(typeof(List<Data.Sources.PromptResult>)))
{
Type type = typeof(List<Data.Sources.PromptResult>);
Object obj = dataObject.GetData(type);
return (List<Data.Sources.PromptResult>)dataObject.GetData(type);
}
The GetFormats()
shows the format as being in the list and the GetDataPresent(List<Data.Sources.PromptResult>)
returns true but if I try to get the object out of the Clipboard
class with GetData(List<Data.Sources.PromptResult>)
I get a return of null.
Does anyone have any idea what might be wrong?
OK I tried to add list of my user type to clipboard and get it back... Here is what I tried:
My User Class:
public class User
{
public int Age { get; set; }
public string Name { get; set; }
}
Rest of Code:
// Create User list and add some users
List<User> users = new List<User>();
users.Add(new User { age = 15, name = "Peter" });
users.Add(new User { age = 14, name = "John" });
// Lets say its my data format
string format = "MyUserList";
Clipboard.Clear();
// Set data to clipboard
Clipboard.SetData(format, users);
// Get data from clipboard
List<User> result = null;
if (Clipboard.ContainsData(format))
result = (List<User>)Clipboard.GetData(format);
...and result was null
:)
...until I marked User
class as Serializable
[Serializable]
public class User
{
//...
}
After that my code worked. Ok its not the answer but maybe it helps you some how.