Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto save and auto load all properties in winforms C#?

Tags:

c#

winforms

How to auto save all properties winforms when closed and auto load all properties winforms when load ? C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < Controls.Count; i++)
            {
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Controls[i]));
                Stream stream = File.Open("test.xml", FileMode.Create);
                x.Serialize(stream, Controls[i]);
            }
        }
    }
}
like image 648
monkey_boys Avatar asked Dec 05 '25 10:12

monkey_boys


1 Answers

Your question is a little unclear, but

If you require saving/loading of the Form Layout have a look at

Windows Forms User Settings in C#

If you require saving/loading an object/class have a look at

Load and save objects to XML using serialization

EDIT:

This will show you how to persist certain settings for form properties.

Save and Restore Setings of a .NET Form using XML

Also have a look at The Application Automation Layer - Using XML To Dynamically Generate GUI Elements--Forms And Controls

All these will guide you in the direction you need to go.

I think the main objective here is

  • Figure out when to save and when to load, and where to store/retrieve these settings.
  • Are you storing these settings per user? In a database? In a xml file?
  • Next you need to identify which properties you will be saving/restoring per control. Simple location/size settings might not cut it as controls will have various complexities (Button, TextBox, Gridview, ListView)
  • Now you need to figure out how to iterate ALL controls on the form. Buttons, Textboxes, Panels, Controls in Controls (controls in panels), and maybe even your User Controls. This can be done using recursion.
  • Now you need to decide on the structure of the xml file (if you opt to use xml). This should pretty much look like a tree structure, as you would look at the form, and its controls, and their controls, as a tree structure.
like image 72
Adriaan Stander Avatar answered Dec 07 '25 00:12

Adriaan Stander