如何在Settings.Default?</string>上保存List <string>

时间:2010-05-23 00:28:19

标签: c# .net winforms

我的表单上有一个ListBox,我想保存它并在我再次启动应用程序时加载值。

如何在PrjName.Properties.Settings.Default上保存列表?

4 个答案:

答案 0 :(得分:77)

完全没问题! 创建一个新设置,例如“MyListOfStrings”,类型并不重要。

enter image description here

然后在xml编辑器中打开设置文件

enter image description here enter image description here

您的文件将如下所示:

enter image description here

现在更改它,如下所示并保存

enter image description here

嗯,就是这样,现在看起来就像那样:

enter image description here

并在代码中:

enter image description here

答案 1 :(得分:41)

我发现我无法在应用程序设置上直接保存List<string>,但我发现我可以保存StringCollection

here我发现从StringCollection转换为List<string>

非常简单
var list = stringCollection.Cast<string>().ToList();

答案 2 :(得分:0)

使用本机支持的Type System.Collections.Specialized.StringCollection

我使用了这段代码:

        System.Collections.Specialized.StringCollection SavedSearchTerms = new System.Collections.Specialized.StringCollection();

        if (Properties.Settings.Default.SavedSearches != null)
        {
            SavedSearchTerms = Properties.Settings.Default.SavedSearches;
        }

        SavedSearchTerms.Add("Any Value");

        Properties.Settings.Default.SavedSearches = SavedSearchTerms;

答案 3 :(得分:0)

我知道这是一个比较老的问题,但是我觉得值得一提的是,您可以创建一个自定义类,该类继承要使用的任何种类的列表,并且设置起来非常简单。例如,如果您想使用List<CustomData>,则可以创建这样的类:

using System.Collections.Generic;

namespace YourNamespace
{
    public class CustomCollection : List<CustomData>
    {
    }
}

然后打开建议的设置,例如@ pr0gg3r并将其添加到<Settings>部分:

    <Setting Name="SomeSetting" Type="YourNamespace.CustomCollection" Scope="User">
      <Value Profile="(Default)" />
    </Setting>

除非它是基本数据类型(例如字符串或整数),否则您将无法使用设置设计器。如果您使用的是自定义数据类型,则必须在启动时对其进行初始化,然后再使用它,但是我发现它看起来比尝试直接在设置中直接使用列表更为优雅。