views:

35

answers:

3

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?

+2  A: 

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

Fyodor Soikin
+1  A: 

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.

Matthew Ferreira
A: 

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

Paul Betts