Click here to Skip to main content
15,041,393 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do i save and load data in C# using the system recources and strings?, eg, I click a button that makes a label says "WoW is Fun!" and another that says "No mincraft is better" and another button that will save the data of the labels text for next time when the program is launched. can anyone please help?
Posted

Just take a look at C# Settings.settings in Visual Studio[^] link.

I hope this will help you well.
   
If you have only a few labels, you can use the property settings that are easily accessible from every application. Right click the application in Visual Studio and go to the Properties tab, add a new property and give it a name, say "Label1". Similarly, create properties for each of your labels. Then in code, you save the labels, like this:

Properties.Settings.Default.Label1.Value = Label1.Text;
Properties.Settings.Default.Label2.Value = Label2.Text;
etc.
Properties.Settings.Save();

To load properties is just as easy:

Label1.Text = Properties.Settings.Default.Label1.Value;
Label2.Text = Properties.Settings.Default.Label2.Value;
etc.


If you have a variable number of labels, then you could concatenate them into a list, like this:

string myLabelList = Label1.Text + "|" + Label2.Text + "|" + etc.

Then you can save that big string to a field you created in Properties, just like above. When you load it you would have to split the string. You can use the Split() method of string for this.


If you have lots of labels to save, then you might consider adding them to a DataSet then serializing the dataset.

MIDL
using System.Data;

DataSet d = new DataSet();
DataTable t = new DataTable();
d.Tables.Add(t);
t.Columns.Add(new DataColumn("Labels", typeof(string)));
t.Rows.Add("asdf");
t.Rows.Add("asdfa");
d.WriteXml("MySavedLabels.xml");


Then later you can retrieve the saved labels like this:

C#
DataSet d = new DataSet();
d.ReadXml("MySavedLabels.xml");
foreach (DataRow row in d.Tables[0].Rows)
{
    string myLabel = (string)row["MyLabel"];
    (do something here with the retrieved label myLabel);
}
   
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900