【问题标题】:C# .Net Save a ListView using Settings.settingsC# .Net 使用 Settings.settings 保存 ListView
【发布时间】:2016-11-06 21:35:34
【问题描述】:

我正在尝试使用 C# .Net 保存和加载 ListView 列表的内容。我希望通过创建一个变量 System.Windows.Forms.ListView 然后用它填充它来保存它。

用于保存的代码 sn-p:

Properties.Settings.Default.followedUsersSettings = followerList;
Properties.Settings.Default.Save();

加载代码 sn-p:

if (Properties.Settings.Default.followedUsersSettings != null) {
            followerList = Properties.Settings.Default.followedUsersSettings;
        }

我似乎无法使用该代码使其工作。有没有更好的方法来保存这个尽可能简单?该列表是单列,因此 Array 也应该可以工作,但我不确定推荐什么。

【问题讨论】:

  • 什么是followerList?
  • 内容是什么?只是一个字符串列表还是有子项?
  • @TaW 内容只是使用 System.Windows.Forms.Listview 的简单字符串列表。没有子项

标签: c# .net listview persistent-storage


【解决方案1】:

好的,我设法让它工作了。

保存:

//Convert the listview to a normal list of strings
var followerList = new List<string>();

//add each listview item to a normal list

foreach (ListViewItem Item in followerListView.Items) {
     followerList.Add(Item.Text.ToString());
}

//create string collection from list of strings
StringCollection collection = new StringCollection();

//set the collection setting (created in Settings.settings as a specialized collection)
Properties.Settings.Default.followedUsersSettingsCollection = collection;
//persist  the settings
Properties.Settings.Default.Save();

对于加载:

//check for null (first run)
if (Properties.Settings.Default.followedUsersSettings != null) {
    //create a new collection again
    StringCollection collection = new StringCollection();
    //set the collection from the settings variable
    collection = Properties.Settings.Default.followedUsersSettingsCollection;
    //convert the collection back to a list
    List<string> followedList = collection.Cast<string>().ToList();
    //populate the listview again from the new list
    foreach (var item in followedList) {
        followerListView.Items.Add(item);
    }
}

希望这对通过 Google 搜索找到此内容的人有意义。

【讨论】:

  • 但是当 collection 变量为空时,你什么也得不到,是吗?
【解决方案2】:
if (Properties.Settings.Default.followedUsersSettingsListView == null)
{
    // adding default items to settings 
    Properties.Settings.Default.followedUsersSettingsListView = new System.Collections.Specialized.StringCollection();
    Properties.Settings.Default.followedUsersSettingsListView.AddRange(new string [] {"Item1", "Item2"});
    Properties.Settings.Default.Save();
}
// load items from settings 
followerList.Items.AddRange((from i in Properties.Settings.Default.followedUsersSettingsListView.Cast<string>()
                                    select new ListViewItem(i)).ToArray());

【讨论】:

  • 抱歉,可能应该更好地命名我的变量。 followerList 是表单上显示的 ListView。 followedUsersSettingsListView 是 Settings.settings 中使用的变量的名称
猜你喜欢
  • 2012-10-21
  • 1970-01-01
  • 2011-04-30
  • 2010-12-24
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多