How to Save TextBox, Label and CheckBox in User Settings in C#

By FoxLearn 11/20/2024 12:43:19 PM   11.39K
To save and load values from TextBox, Label, and CheckBox controls in user settings in a Windows Forms application, you can use the built-in Properties.Settings feature in C#.

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "UserSettingDemo" and then click OK

Drag and drop the CheckBox, Label, TextBox, Button controls from the Visual Toolbox onto your form designer, then design your form as shown below.

c# user settings

Go to Project > Properties > Settings tab.

Add entries for each control's value you want to save like this:

user settings in c#

The .NET Framework 2.0 enables the creation and management of settings, which are values persisted across application sessions. These settings can store user preferences or essential application data.

Settings in .NET allow you to persist critical application data, such as user preferences or essential configuration details. They also enable the creation of user-specific profiles for personalized experiences.

You can save the current state of the controls when the form is closing or when needed.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    //Save data to user settings
    Properties.Settings.Default.CheckBox = chkRememberPassword.Checked;
    Properties.Settings.Default.Title = txtTitleForm.Text;
    Properties.Settings.Default.Label = txtValue.Text;
    Properties.Settings.Default.TextBox = txtValue.Text;
    Properties.Settings.Default.PX = this.Location.X;
    Properties.Settings.Default.PY = this.Location.Y;
    Properties.Settings.Default.Save();
}

private void btnSetTitleForm_Click(object sender, EventArgs e)
{
    this.Text = txtTitleForm.Text;
}

private void btnSetValueLable_Click(object sender, EventArgs e)
{
    lblValue.Text = txtValue.Text;
}

Load the settings when the form initializes or on application start.

private void Form1_Load(object sender, EventArgs e)
{
    // Load data from user settings
    Text = Properties.Settings.Default.Title;
    chkRememberPassword.Checked = Properties.Settings.Default.CheckBox;
    lblValue.Text = Properties.Settings.Default.Label;
    txtValue.Text = Properties.Settings.Default.TextBox;
    this.Location = new Point(Properties.Settings.Default.PX, Properties.Settings.Default.PY);
}

This approach uses Properties.Settings, which is ideal for user-level settings in a Windows Forms application.

VIDEO TUTORIAL