1

I create winform and its control created in run time based on some data passed to the form.
I don't know the number of controls will be created also the type of control.
The data passed to form just text and i make some condition to check create label or textbox or button.

I want to save this controls name, Location,Text. This controls can be textbox,button, label,ComboBox.

How can i make that ? if XmlSerializer can be valid in this case? if yes how can use it?
Can anyone give me a bit of code or link ?

Ahmed
  • 305
  • 5
  • 14
  • 2
    I would serialise the controls to JSON and store the resulting text. This should get you started: http://stackoverflow.com/questions/15843446/c-sharp-to-json-serialization-using-json-net – Ulric Sep 15 '15 at 08:38
  • KISS: you could also save the data that created the controls and reprocess? – Falco Alexander Sep 15 '15 at 08:41
  • possible duplicate of [How I can save controls created in run time in Windows Forms](http://stackoverflow.com/questions/10739641/how-i-can-save-controls-created-in-run-time-in-windows-forms) – Falco Alexander Sep 15 '15 at 08:44
  • So there's a relationship between your created controls and "some data passed", is storing those data easier ? – Nam Bình Sep 15 '15 at 08:49
  • @NamBình I don't know the number of controls will be created also the type of control. The data passed to form just text and i make some condition to check create label or textbox or button. – Ahmed Sep 15 '15 at 08:50
  • So basically you could save the text and then do the same analysis again..? – TaW Sep 15 '15 at 09:00
  • @TaW Yes i can make that, but i want to make the analysis occur one time – Ahmed Sep 15 '15 at 09:03
  • Of course, especially if it is complex. But you can and should simply store the results as text, maybe key-value pairs and when restoring you have a simpler job. You can't store the controls as binary data because they simply are not. You may want to study the Designer.CS file to see how studio is storing its forms etc.. – TaW Sep 15 '15 at 09:37

1 Answers1

2

Controls aren't designed to be saved. so you can't do this with the controls themselves, but if you write a class that contains whatever details you need from the control then you can save and use them however you want. just mark them as serializable and feed them into a stream writer and reader (https://msdn.microsoft.com/en-gb/library/ms233843.aspx)

[Serializable]
class ControlFactory
{
    enum ControlType
    {
        TextBox
    }
    ControlType Type {get;set;}
    Point Position {get;set;}
    //etc.
    Control Create()
    {
        switch(Type)
        {
            case ControlType.TextBox:
                TextBox txt = new Textbox();
                // apply settings
                return txt;
        }
    }
}
MikeT
  • 5,398
  • 3
  • 27
  • 43