【问题标题】:How do I save user settings of combobox in C#?如何在 C# 中保存组合框的用户设置?
【发布时间】:2021-11-04 10:56:17
【问题描述】:

我无法像 TextBox 或 CheckBox 一样保存 ComboBox 的用户设置?该怎么做?

【问题讨论】:

标签: csharpcodeprovider


【解决方案1】:

这是一个使用 .NET 5 的简单示例。

我创建了一个带有 ComboBox ("comboBox1") 和 Button ("bnAdd") 的表单,用于将用户输入的值添加到 ComboBox。

我添加了一个名称为“ThepphuongWCombo”的设置,类型为“String”,范围为“User”。

当窗体关闭时,来自 ComboBox 的数据被保存,保存的数据在应用运行时被加载。

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

    }
}

【讨论】:

  • 谢谢兄弟!我做到了 !我使用 combobox.selectedIndex!
猜你喜欢
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多