How can I save and then read UserControl that were created dynamically, at run time? in C #, WindowsForms

0

I need to know how and where is the most optimal way in which I can go GUARDING controls (Buttons, Layouts, Label etc) , and mainly also UserControl that were created in time of execution. The funny thing is that ONCE THE PROGRAM IS CLOSED , when you open it again, you can interact again with those controls that were added dynamically, that is, that the closed program does not interfere in its dynamism. .-

    
asked by JaviYeri 17.06.2018 в 06:27
source

2 answers

0

The most viable, simple and practical way is to do it through Json.Net . It is a library, downloadable from Nuget (.NET Package Manager), which allows me to work with the Json format. The way I will do it is to write dynamically in a Json every time I create a control. Then when I close and reopen the program I simply charge from that Json the controls. The only disadvantage is the disk puncture that sends me every time I do a back-up (which is much more than slow to work it in RAM), but if or if I should move that info to disk, so that work should be done.

    
answered by 21.06.2018 / 07:46
source
1

You can mark the class as serializable with [SERIALIZE], even though the buttons can not be serialized you will have to mark them in this way "[NonSerialized] Button btn = new Button ();" I enclose a code fragment that could help you

 IFormatter formatter = new BinaryFormatter();
        String directorio = Environment.CurrentDirectory + "..\Listas";

            PARA GUARDAR
                saveFileDialog1.InitialDirectory = directorio;
                saveFileDialog1.FileName = "";
                saveFileDialog1.Filter = "(*.btn)|*.btn";
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Stream stream = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None);
                    formatter.Serialize(stream, "TU OBJETO DE LA CALSE VA AQUI");
                    stream.Close();
                }
                break;

            PARA ABRIR
                openFileDialog1.FileName = "";
                openFileDialog1.Filter = "(*.btn)|*.btn";
                openFileDialog1.InitialDirectory = directorio;
                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    g.Clear(BackColor);
                    grafo.Clear();
                    Stream stream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.None);
                    grafo = ("TU OBJETO DE LA CALSE VA AQUI")formatter.Deserialize(stream);
                    stream.Close();

                    "AQUI RECONSTRUYES TODOS TUS BOTONES, YA QUE UN OBJETO BOTON NO ES SERIALIZABLE"
                    Invalidate();
                }
    
answered by 18.06.2018 в 19:27