marking a WinForms Button as serializable

This is my very first program for serialization.

An error occurred when trying to serialize a button control.

public Form1()
{
     InitializeComponent();
     CheckSerialization();                
     Button btn = btnSerialized;            
}

public void CheckSerialization()
{
     Stream write = File.OpenWrite(@"C:\ser.bin");
     BinaryFormatter serial = new BinaryFormatter();
     serial.Serialize(write, btnSerialized);
     write.Close();
}

private void btnSerialized_Click(object sender, EventArgs e)
{
     FileStream fs = new FileStream(@"C:\ser.bin",FileMode.Open);
     BinaryFormatter bf= new BinaryFormatter();
     object obj = bf.Deserialize(fs);
     Button button12 = (Button)obj;
     button1 = button12;
     button1.Location = new Point(0, 0);
}

Type 'System.Windows.Forms.Button' in Assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.**

How do I mark this object as serializable?

Answers


Find the line that looks like public partial class Form1 : Form. Right above it, place [Serializable]. That marks your class for serialization. You will need to control your own serialization however, since as noted below, UI objects do not serialize. For that, look at the ISerializable interface.

More information about SerializableAttribute is here.


You don't. The type must be marked as Serializable, not the object.


You can't serialize Winforms objects (or other UI objects, generally speaking)


IF you are trying to export the object or reload the object with user provided property values for dynamicity then why dont' you use System.Reflection. Here: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime


Need Your Help

Canvas toBlob is not recognized as a function in Chrome or IE

javascript jquery html canvas

I'm using Cropper to get the blob for a cropped image. I'm using the latest versions of Chrome and IE, but I'm getting 'canvas.toBlob is not a function' in Chrome and 'Object doesn't support proper...

Laravel routing & filters

laravel filter laravel-routing

I want to build fancy url in my site with these url patterns: