2016-11-06 7 views
0

C#.Netを使用してListViewリストの内容を保存して読み込もうとしています。私は変数System.Windows.Forms.ListViewを作成し、それにそれを設定して保存することを望んでいました。保存のためのC#.Net Settings.settingsを使用してリストビューを保存する

コードスニペット:ロード用

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

コードスニペットは:

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

私はそれがそのコードを使用して動作するように見えることはできません。できるだけシンプルにこれを保存する方法がありますか?リストは単一の列なので、配列も機能するはずですが、何が推奨されているのか分かりません。

+1

followerListとは何ですか? – Damith

+0

コンテンツとは何ですか?文字列のリストまたはサブアイテムがありますか? – TaW

+0

@TaWコンテンツは、System.Windows.Forms.Listviewを使用した文字列の単純なリストです。副題はありません – Avendor7

答えて

1

ok、私はそれを動作させることができました。

省:

//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検索からこれを見つけた誰かに理にかなっています。

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

関連する問題