How do I save user settings of combobox in C#?

426 Views Asked by At

I can't save User Setting of ComboBox like the TextBox or CheckBox? How to do that?

Application settings page showing no entry for a setting type of ComboBox

1

There are 1 best solutions below

1
Andrew Morton On

This is a simple example using .NET 5.

I created a form with a ComboBox ("comboBox1") and a Button ("bnAdd") to add a user-entered value to the ComboBox.

I added a setting with a name of "ThepphuongWCombo", type "String", and scope "User".

When the form is closed, the data from the ComboBox is saved, and the saved data is loaded when the app is run.

using System;
using System.Text.Json;
using System.Windows.Forms;

namespace SaveComboBoxToJson
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

         private void bnAdd_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Add(comboBox1.Text);
        }

        private void SaveUserData()
        {
            var json = JsonSerializer.Serialize(comboBox1.Items);
            Properties.Settings.Default.ThepphuongWCombo = json;
            Properties.Settings.Default.Save();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Show the location of the settings file being used in case you want to inspect it.
            //var path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
            //MessageBox.Show(path);

            var cbData = Properties.Settings.Default.ThepphuongWCombo;
            if (string.IsNullOrEmpty(cbData))
            {
                // Add some default values.
                comboBox1.Items.Add("CCC");
                comboBox1.Items.Add("DDD");
            }
            else
            {
                var itms = (object[])JsonSerializer.Deserialize(cbData, typeof(object[]));
                comboBox1.Items.AddRange(itms);
            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveUserData();
        }

    }
}