0

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

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Do you need to save all the items of the ComboBox or only one item? – Andrew Morton Sep 07 '21 at 14:39
  • I want to save all the Items of the Combobox! Thanks for respond! – PhilipZone Sep 08 '21 at 11:02
  • You could serialize the ComboBox's data to JSON, which is a string that can be stored in the settings. You might find [Deserialize json object from a combobox data (loaded from database) Winform](https://stackoverflow.com/q/60235716/1115360) useful too. – Andrew Morton Sep 08 '21 at 11:09

1 Answers1

0

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();
        }

    }
}
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84