Once you learn how to use a DataContractSerializer, I predict you'll use it frequently.
Keep in mind that WinForm Control instances will not serialize directly; however, you can save most Properties of most of the Controls. For example, you can save Properties of the 'Font, like Font.Name, etc.
All WinForm Controls inherit from 'Control: so, for any Control, Properties like 'Name, 'Text can be accessed. A specific Control may have Properties it does
not inherit from Control: for example, a TextBox has a BorderStyle Property; cast it into 'Control, and that property is not exposed.
So, the strategy is to save the Properties of Controls that you can use, then, restore the state of those Properties as needed to restore the Control/
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Windows.Forms;
namespace YourNameSpace
{
[DataContract]
public class ControlNameText
{
public ControlNameText(Control cntrl)
{
Name = cntrl.Name;
Text = cntrl.Text;
}
[DataMember]
public string Name { set; get; }
[DataMember]
public string Text { set; get; }
}
[DataContract]
public static class ControlsSaveLoad
{
private static string baseFolderPath = @"C:\Users\test_user\Desktop\Test\test.xml";
private static DataContractSerializer dcs = new DataContractSerializer(typeof(List<ControlNameText>));
[DataMember] public static List<ControlNameText> Cntrls = new List<ControlNameText>();
public static void Save(Form frm)
{
foreach (Control cntrl in frm.Controls.OfType<TextBox>())
{
Cntrls.Add(new ControlNameText(cntrl));
}
using (var writer =
new FileStream(baseFolderPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
dcs.WriteObject(writer, Cntrls);
}
}
public static void Load(Form frm)
{
using (var reader = new FileStream(baseFolderPath, FileMode.Open, FileAccess.Read))
{
Cntrls = (List<ControlNameText>) dcs.ReadObject(reader);
}
foreach (ControlNameText cntrl in Cntrls)
{
frm.Controls[cntrl.Name].Text = cntrl.Text;
}
}
}
}
Use example:
private void Form1_Load(object sender, EventArgs e)
{
ControlsSaveLoad.Load(this);
}
I suggest you study this example carefully; saving the ComboBoxes 'SelectedText Property can be implemented the same way. I expect you to implement this example and research each step of the solution.
Notes:
0) this code omits the error trapping/handling necessary for real-world use: you should implement checking for FileNotFoundError, etc.
1) the search for TextBoxes only gets the ones in the top-Level Form.ControlCollection.
2) I will not explain. or extend, this code further; however, I will answer questions from you that show you have studied this solution, run it, and done research on how it works.