This is a built-in mechanism for this, called Application Settings
.
So you have a form with two labels, of which Label2
holds the value. The button button1
increments the value.

Go to the project settings and create one string
setting called CounterText
.

Now we need three event handlers for the form.
When the form loads, we want to connect the contents of label2
with the CounterText
setting
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Update the label automatically from the setting
label2.DataBindings.Add("Text", Properties.Settings.Default, "CounterText", true,
DataSourceUpdateMode.OnPropertyChanged);
}
When the form closes you want to save the settings
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
// Save the settings before exit
Properties.Settings.Default.Save();
}
When the button is clicked you want to increment the value in the settings
private void button1_Click(object sender, EventArgs e)
{
// Read the setting value (string->int)
if (int.TryParse(Properties.Settings.Default.CounterText, out int num))
{
// Increment value
num++;
// Update the setting (int->string)
Properties.Settings.Default.CounterText = num.ToString();
// The system will automatically update the label text.
}
}
Now every time the form runs, it will read the application settings and set the value of the text label correctly. Also when the button is pressed and the setting is changed, the label is updated automatically because if the DataBindings
defined.

What happens in the background is that an XML file is saved under %appdata%\Local\WindowsFormsApp1\1.0.0.0\user.config
or whatever the name of your application is. The contents are as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<WindowsFormsApp1.Properties.Settings>
<setting name="CounterText" serializeAs="String">
<value>3</value>
</setting>
</WindowsFormsApp1.Properties.Settings>
</userSettings>
</configuration>
You can clearly see the value of CounterText being saved as 3 in this case. This file gets read in when the program starts (automatically) and updated when the program ends (manually).