Reputation: 15
In C#, how can I save the checkstate value of checkboxes and radio buttons or text value in textboxes and richtextboxes in a single file? If it is even possible at all? How can I then make it possible for the user to load that file back into the software so all the values go back to the same checkboxes, and textboxes they were saved from?
Upvotes: 0
Views: 1088
Reputation: 770
You can do it in this (basic) way: Just use a xml to store the data to and then read it back from the xml to access the objects data.
1.) Build a class for the data
[Serializable()]
[XmlRoot("MyData", Namespace = "")]
public class MyData
{
public MyData() { }
public bool checkBox1State { get; set; }
public bool checkBox2State { get; set; }
public string radioGroupSelected { get; set; }
public string button1Text { get; set; }
...
}
Then build 2 methods for reading and writing the xml file:
public static class MyDataWorker
{
public static MyData ReadMyData()
{
XmlSerializer reader = new XmlSerializer(typeof(MyData));
System.IO.StreamReader file = new System.IO.StreamReader("MyData.xml");
MyData data = new MyData();
data = (MyData)reader.Deserialize(file);
file.Close();
return data;
}
public static void WriteMyData(MyData data)
{
XmlSerializer writer = new XmlSerializer(typeof(MyData));
System.IO.StreamWriter file = new System.IO.StreamWriter("MyData.xml");
writer.Serialize(file, data);
file.Close();
}
}
Usage:
// Create data object instance
MyData data = new MyData();
// Fill Data from controls
data.checkBox1State = checkBox1.Checked;
...
// Write File to XML
MyDataWorker.WriteMyData(data);
// Read File to MyData object
MyData data = MyDataWorker.ReadMyData();
Further steps could be, extending the functions with parameters to read/write specific XML files to different paths.
So far for a small wrap up.
Upvotes: 1