Reputation: 314
I am trying to copy paste a control instance using the clipboard. I am able to copy the control but unable to get back the copied object.
Sample code below.
[Serializable]
public class myControl
{
private Control _copiedControl;
public myControl(Control ctrl)
{
_copiedControl = ctrl;
}
public Control CopiedControl
{
get
{
return _copiedControl;
}
set
{
_copiedControl = value;
}
}
}
private void btnCopy_Click(object sender,EventArgs e)
{
Clipboard.SetData("myControl", new myControl((Control)myButton));
}
private void btnPaste_Click(object sender, EventArgs e)
{
if(Clipboard.ContainsData("myControl"))
{
// Condition is satisfied here..
myControl obj = Clipboard.GetData("myControl") as myControl;
// obj is null and control is lost..
if(obj != null)
{
myPanel.Controls.Add(obj.CopiedControl);
}
}
}
I am unable to get the copied control using the GetData() method. I am not sure what is wrong can anyone guide me?
Upvotes: 1
Views: 2424
Reputation: 941237
You marked your "myControl" serializable but it is not in fact serializable, the Control class does not support binary serialization. Way too much trouble with the runtime state for the window associated with the control, starting with the fact that a window can only ever have a single parent. Sadly the Clipboard.SetData() method does not complain about that.
There's a pretty simple workaround for it, the clipboard can only contain a single item and copying between processes is never going to work. So you might as well fake it and keep your own reference to the control. Something like this:
private Control clipBoardRef;
private void btnCopy_Click(object sender, EventArgs e) {
clipBoardRef = myButton1;
Clipboard.SetData("myControl", "it doesn't matter");
}
private void btnPaste_Click(object sender, EventArgs e) {
if (Clipboard.ContainsData("myControl")) {
Control ctl = clipBoardRef;
// etc...
}
}
Upvotes: 2