2014-07-15 54 views
0

我想保存並加載到.NET設置文件(app.config)的組合框項目列表。C#:保存並從app.config文件加載組合框項目列表

用下面的代碼,我想加載和保存存儲在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(); 
} 

當我打開項目的屬性頁面,然後選擇設置選項卡,我想用來存儲{ 「myItem1」, 「myItem2」, 「myItem3」}在一個ArrayList cboCollection。不幸的是,沒有這種類型的System.Collections.ArrayList可供選擇。我做錯了什麼?

+0

你把這段代碼從[這裏](http://stackoverflow.com/questions/376622/c-how-do-you-save-a -list-of-items-like-a-combobox-to-the-net-settings-file)並詢問爲什麼它不起作用。對不起,你應該閱讀這個答案,瞭解你做錯了什麼,我不會告訴你的。 –

+0

是的,我讀過它,但遺憾的是我並沒有完全理解它。它說_如果你使用ArrayList,它的所有元素的類型必須是可序列化的(具有[Serializable]屬性或實現System.Runtime.Serialization.ISerializable。)_。我添加了'使用System.Runtime.Serialization'。我需要在哪裏獲得[Serializable]屬性? – Boozzz

+0

cboCollection是這個人制作的對象的名稱,你應該實現你的並在其上添加[Serializable]。 –

回答

1

首先,你沒有做任何事情。您從here獲取了此代碼。

它不起作用,因爲您沒有執行cboCollection對象。

首先你需要一個設置 enter image description here

然後實現你的類

[Serializable] 
public MyClass 
{ 
//something... 
} 

編輯: OK,忘掉類,只是使用System.Collections.Specialized.StringCollection。這樣您可以將項目添加到設置。

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

通過循環每個項目,將您的組合框項目填充到itemList中。

,然後你可以做如下:

Settings.Default.cboCollection = itemList; 
+0

什麼是MyClass應該做什麼以及它應該在哪裏實現? – Boozzz

+0

我知道我從[這裏]取了這段代碼(http://stackoverflow.com/questions/376622/c-how-do-you-save-a-list-of-items-like-a-combobox-to -the-net-settings-file),我不認爲這有什麼問題,因爲我從來沒有說過我是自己做的。我仍然沒有得到你的答案,因爲你不想告訴我一個答案。無論如何,我發現一個解決方案[這裏](http://www.c-sharpcorner.com/Forums/Thread/104121/combobox-problem.aspx),對於那些誰會有同樣的問題。 – Boozzz