2016-11-06 31 views
0

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

保存代码片段:用于加载

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

代码片段:

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

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

+1

什么是followerList? – Damith

+0

内容是什么?只是一个字符串列表或有子项? – TaW

+0

@TaW内容只是一个简单的使用System.Windows.Forms.Listview的字符串列表。没有子条目 – Avendor7

回答

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

希望这是有道理的人谁发现这个来自谷歌搜索。

0
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()); 
+0

对不起,可能应该更好地命名我的变量。 ** followerList **是在窗体上显示的ListView。 ** followUsersSettingsListView **是Settings.settings中使用的变量的名称 – Avendor7

+0

@ Avendor7检查我的更新 – Damith