Question

I have an windows forms app in C# where I can add multiple controls at runtime. What is the best/easiest way to save all the changes after I close my app? Basically if I add two buttons at runtime, after I close the app and open it again, I should have those tow buttons there with all functions and settings.

Can you recommend some possible solutions to achieve this?

Was it helpful?

Solution

well actually if you want to add unknown number of controls to you form at run-time and then recreate them again at next run actually you can.

One of the ways to write objects to hard disk and load them again. you can do that using serialization. unfortunately you cannot serialize controls objects but you can create some class that's holds the common properties like {type,location,size,forecolor,backcolor}.

at exit create a list and create an object to hold each control properties then add the object to the list at the end serialize the whole list.

Check These Links to know more about serialization What is [Serializable] and when should I use it?

http://www.dotnetperls.com/serialize-list

and also i can provide you with this code that should help you to get the idea

    [Serializable]//class to hold the common properties
    public class Saver
    {
        public Saver() { }
        public Point Location { get; set; }
        public Type Type { get; set; }
        public Size Size { get; set; }
        public string Text { get; set; }
        //add properties as you like but maker sure they are serializable too
    }

The following two functions to save and load the data

    public void SaveControls(List<Control> conts, Stream stream)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<Saver> sv = new List<Saver>();

        foreach (var item in conts)
        {
            //save the values to the saver object
            Saver saver = new Saver();
            saver.Type = item.GetType();
            saver.Location = item.Location;
            saver.Size = item.Size;
            saver.Text = item.Text;

            sv.Add(saver);
        }

        bf.Serialize(stream, sv);//serialize the list
    }

This is the second one

    public List<Control> LoadControls(Stream stream)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<Saver> sv =(List<Saver>) bf.Deserialize(stream);

        List<Control> conts = new List<Control>();

        foreach (var item in sv)
        {
            //create an object at run-time using it's type
            Control c = (Control)Activator.CreateInstance(item.Type);

            //reload the saver values into the control object
            c.Location = item.Location;
            c.Size = item.Size;
            c.Text = item.Text;

            conts.Add(c);
        }

        return conts;

    }

OTHER TIPS

You can save some XML file that will describe a context of your application

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top