C#:如何将像Combobox这样的项目列表保存到.NET设置文件中?

5 c#

C#:如何将像Combobox这样的项目列表保存到.NET设置文件中?

fos*_*son 10

Settings Designer允许您使用的唯一集合类型是System.Collections.ArrayList.如果使用ArrayList,则其所有元素的类型必须是可序列化的(具有[Serializable]属性或实现System.Runtime.Serialization.ISerializable.)

这里有一些代码可以将来自SettingsList中的ArrayList(名为cboCollection)的数据导入组合框并返回.

    private void Form1_Load(object sender, EventArgs e)
    {
        if (Settings.Default.cboCollection != null)
            this.comboBox1.Items.AddRange(Settings.Default.cboCollection.ToArray());
    }


    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        ArrayList arraylist = new ArrayList(this.comboBox1.Items);
        Settings.Default.cboCollection = arraylist;
        Settings.Default.Save();
    }

    //A button to add items to the ComboBox
    private int i;
    private void button1_Click(object sender, EventArgs e)
    {
        this.comboBox1.Items.Add(i++);
    }
Run Code Online (Sandbox Code Playgroud)


Zac*_*tes 4

如果您正在谈论应用程序用户设置,我将循环组合框并将值保存在分隔字符串中:

StringBuilder sb = new StringBuilder();
foreach(var item in combo.Items){
  sb.Append(item.ToString() + ";");
}
Properties.Settings.MyListSetting = sb.ToString();
Run Code Online (Sandbox Code Playgroud)

上面的代码只是一个例子,如有不完善之处,敬请谅解。

希望有帮助!