I have been working on an application which allows the user to make a label template for printing purposes by adding label controls to a panel(which I use as a container). I ha
You can get the position, size and other properties about the form's controls at runtime and save that state in an XML or JSON file.
Try this. It uses the ISerializationSurrogate interface to get around the problem of the form object not being serializable:
How to serialize an object which is NOT marked as 'Serializable' using a surrogate. http://www.codeproject.com/KB/dotnet/Surrogate_Serialization.aspx
I wouldn't directly serialize a form to a file. Sounds like you need to create a class that will hold the state of the user's work. You should then serialize that class to and from a file. There are built in methods for that using either Binary or XML Serialization.
This isn't trivial, but personally I would set up a function that can be called recursively that would add nodes to an XML file.
I don't have actual code, but pseudo-code looks like this: (you will need to do some clean-up, because I'm doing this off the top of my head without the aid of Intellisense.)
XmlDocument doc;
function SaveForm()
{
doc = new XmlDocument("FormInfo");
foreach(Control ctrl in this.Controls)
{
AddControlToXml(ctrl, doc.Documentelement);
}
}
function AddControlToXml(Control ctrl, XmlNode currentNode)
{
XmlNode n = new XmlNode;
Node.InnerText = ctrl.Name;
foreach(Control ctrl2 in ctrl.Controls)
{
AddControlToXml(ctrl2);
}
}
Personally, I would serialize it as JSON. When bringing it back you can use a generic method that loops through and sets the properties through reflection. Also take notice that the library I've linked to will automatically serialize objects that you pass to it.
JSON
JSON.NET
[{ "Label": [{"Top": 102}, {"Left": 105}, {"Text": "blah, blah"}] }]
From JSON.NET
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Create a struct that contains enough information (and no more) about each Label
that you can reconstitute the Label
from it.
Write a method that takes a List<MyStruct>
and populates a Panel
from your structs.
Write methods to serialize and deserialize this list.
Encapsulate the whole thing in a class.