Saving Windows Form Controls State Using Serialization in C-Sharp

Some time we need to save our dialog & controls state to some file or some other persistable place like database of some memory objects. This we can achieve by serialization given in dotnet. But unfortunately Windows Form or Controls does not support serialization, so we have to do some trick or some coding to do this.

In this post i am going to publish a simple but effective C# class to do this. This class support serialization and de-serialization of very basic controls properties. Actually these properties only needs to serialize.

If you want to add more control’s and properties then you can easily add those properties in this class and you can make your own class.

Here is my Code listing for control serializer.

    public class ControlSerializer
    {
        private Control _control;
        private List<MyControlProp> _props = 
            new List<MyControlProp>();
 
        private List<MyControlProp> Props
        {
            get { return _props; }
            set { _props = value; }
        }
        public Control Control
        {
            get { return _control; }
            set { _control = value; }
        }
 
        public ControlSerializer(Control ctrl)
        {
            this.Control = ctrl;
        }
 
        public void Serialize(string filePath)
        {
            Serialize(this.Control, filePath);
        }
        public void Serialize(Control ctrl, string filePath)
        {
            if (ctrl != null)
            {
                this.Props.Clear();
                ReadPropes(ctrl);
 
                XmlSerializer serializer = 
                    new XmlSerializer(typeof(List<MyControlProp>));
                using (FileStream stream = 
                    new FileStream(filePath, FileMode.Create))
                {
                    serializer.Serialize(stream, this.Props);
                }
            }
            else
            {
                throw new Exception("Please hande this");
 
            }
        }
 
        public void Deserialize(string filePath)
        {
            Deserialize(this.Control, filePath);
        }
        public void Deserialize(Control ctrl, string filePath)
        {
            if (ctrl != null)
            {
                XmlSerializer serializer = 
                    new XmlSerializer(typeof(List<MyControlProp>));
                using (FileStream stream = 
                    new FileStream(filePath, FileMode.Open))
                {
                    object obj = serializer.Deserialize(stream);
                    this.Props = (List<MyControlProp>)obj;
                    WritePropes(ctrl);
                }
            }
            else
            {
                throw new Exception("Please hande this");
            }
        }
 
        private void WritePropes(Control ctrl)
        {
            foreach (MyControlProp item in this.Props)
            {
                Control[] chCtrllist = 
                    ctrl.Controls.Find(item.Name,true);
                if (chCtrllist.Length > 0)
                {
                    item.SetControlValues(chCtrllist[0]);
                }
            }
        }
        private void ReadPropes(Control ctrl)
        {
            MyControlProp prop = new MyControlProp(ctrl);
            this.Props.Add(prop);
            if (ctrl.HasChildren)
            {
                foreach (Control item in ctrl.Controls)
                {
                    ReadPropes(item);
                }
            }
            
        }
        [Serializable]
        public class MyControlProp
        {
 
            private string _name;
            private string _text;
            private int _selectedIndex;
            private bool _disbaled;
            private bool _visible;
            private Color _foreColor;
            private Color _backColor;
            private bool _checked;
            private int _checkState;
 
            public int CheckState
            {
                get { return _checkState; }
                set { _checkState = value; }
            }
            public bool Checked
            {
                get { return _checked; }
                set { _checked = value; }
            }
 
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
 
            public string Text
            {
                get { return _text; }
                set { _text = value; }
            }
 
            public int SelectedIndex
            {
                get { return _selectedIndex; }
                set { _selectedIndex = value; }
            }
 
            public bool Disbaled
            {
                get { return _disbaled; }
                set { _disbaled = value; }
            }
 
            public bool Visible
            {
                get { return _visible; }
                set { _visible = value; }
            }
 
            public Color ForeColor
            {
                get { return _foreColor; }
                set { _foreColor = value; }
            }
 
            public Color BackColor
            {
                get { return _backColor; }
                set { _backColor = value; }
            }
 
            /// <summary>
            /// Parameterless ctr is required to make
            /// class serializable
            /// </summary>
            public MyControlProp()
            { 
            
            }
            /// <summary>
            /// 
            /// </summary>
            /// <param name="ctrl"></param>
            public MyControlProp(Control ctrl)
            {
                GetControlValues(ctrl);
               
            }
 
            /// <summary>
            /// Method to read control values and assign it to object
            /// </summary>
            /// <param name="ctrl"></param>
            public void GetControlValues(Control ctrl)
            {
                if (ctrl == null)
                {
                    throw new Exception(" UnhandledException");
                }
                this.Name = ctrl.Name;
                this.Text = ctrl.Text;
                this.Disbaled = ctrl.Enabled;
                this.Visible = ctrl.Visible;
                this.ForeColor = ctrl.ForeColor;
                this.BackColor = ctrl.BackColor;
                if (ctrl.GetType() == typeof(ComboBox) || 
                    ctrl.GetType() == typeof(ListBox))
                {
                    ListControl lst = (ListControl)ctrl;
                    this.SelectedIndex = lst.SelectedIndex;
                }
                else if (ctrl.GetType() == typeof(CheckBox))
                {
                    CheckBox ch = (CheckBox)ctrl;
                    this.Checked = ch.Checked;
                    this.CheckState = (int)ch.CheckState;
                }
                else if (ctrl.GetType() == typeof(RadioButton))
                {
                    RadioButton btn = (RadioButton)ctrl;
                    this.Checked = btn.Checked;
                }
            }
 
            /// <summary>
            /// Method to set values to controls
            /// </summary>
            /// <param name="ctrl"></param>
            public void SetControlValues(Control ctrl)
            {
                if (ctrl == null)
                {
                    throw new Exception(" UnhandledException");
                }
                
                ctrl.Text = this.Text;
                ctrl.Enabled = this.Disbaled;
                ctrl.Visible = this.Visible;
                ctrl.ForeColor = this.ForeColor;
                ctrl.BackColor = this.BackColor;
                if (ctrl.GetType() == typeof(ComboBox) ||
                    ctrl.GetType() == typeof(ListBox))
                {
                    ListControl lst = (ListControl)ctrl;
                    lst.SelectedIndex = this.SelectedIndex;
                }
                else if (ctrl.GetType() == typeof(CheckBox))
                {
                    CheckBox ch = (CheckBox)ctrl;
                    ch.Checked = this.Checked;
                    ch.CheckState = (CheckState)this.CheckState;
                }
                else if (ctrl.GetType() == typeof(RadioButton))
                {
                    RadioButton btn = (RadioButton)ctrl;
                    btn.Checked = this.Checked;
                }
            }
        }
 
    }

In this class i have created one class MyControlProp in which i have created members to store controls properties values like Name, Text, Selected Index and two method to read and assign control’s property values.

  • public void GetControlValues(Control ctrl)
  • public void SetControlValues(Control ctrl)

To add more properties you can add them in this class and implement them in these methods.

In ControlSerializer i have given two methods to do serialization and de-serialization. I have used XmlSerializer class to do xml serialization and de-serialization but you can use any serialization what you want like binary of any custom.

To use this class just call Serialize and Deserialize methods where you want as shown below.

For serialize
ControlSerializer serializer = new ControlSerializer(this);
serializer.Serialize(@"c:test.xml");
 
For dserialize
ControlSerializer serializer = new ControlSerializer(this);
serializer.Deserialize(@"c:test.xml");
 

Using this class you can serialize any user control or controls on group boxes.

In place of List<T> you can create your own custom list class by to do this but in my opinion it is sufficient for saving dialog state. 

Leave a Reply

Your email address will not be published. Required fields are marked *