![](/img/trans.png)
[英]C# How do you save settings containing multiple objects and bind them to items in a listbox
[英]C#: How do you save a list of items like a Combobox to the .NET Settings file?
C#:如何將組合框等項目列表保存到 .NET 設置文件?
設置設計器允許您使用的唯一集合類型是 System.Collections.ArrayList。 如果您確實使用 ArrayList,則其所有元素的類型都必須是可序列化的(具有 [Serializable] 屬性或實現 System.Runtime.Serialization.ISerializable。)
下面是一些代碼,用於從設置中的 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();
}
//A button to add items to the ComboBox
private int i;
private void button1_Click(object sender, EventArgs e)
{
this.comboBox1.Items.Add(i++);
}
如果您在談論應用程序用戶設置,我會遍歷組合框並將值保存在分隔字符串中:
StringBuilder sb = new StringBuilder();
foreach(var item in combo.Items){
sb.Append(item.ToString() + ";");
}
Properties.Settings.MyListSetting = sb.ToString();
如果上面的代碼不完美,請原諒,這只是一個例子。
希望有幫助!
Windows 窗體對象不可序列化。 因此,您無法使用 binaryformatter 將它們序列化並存儲在文件中。 您需要將組合框值手動存儲在文件中。
string comboboxFileName = @"c:\workDir\settings.settings";
private void saveComboboxInFile (String comboboxFileName )
{
//--------------------------------------------------------
//- Store the combobox values in a file. 1 value = 1 line
//--------------------------------------------------------
try
{
using (StreamWriter comboboxsw = new StreamWriter(comboboxFileName))
{
foreach (var cfgitem in comboBox.Items)
{
comboboxsw.WriteLine(cfgitem);
}
} // End Using`
}
catch (Exception e)
{
//process exception
}
}
private void reloadCombboxFromFile (string comboboxFileName )
{
//-------------------------------------------------
//- Read the values back into the combobox
//-------------------------------------------------
try
{
using (StreamReader comboboxsr = new StreamReader(comboboxFileName))
{
while (!comboboxsr.EndOfStream)
{
string itemread = comboboxsr.ReadLine();
comboBox.Items.Add(itemread);
}
} // End Using
}
catch (DirectoryNotFoundException dnf)
{
// Exception Processing
}
catch (FileNotFoundException fnf)
{
// Exception Processing
}
catch (Exception e)
{
// Exception Processing
}
}
您可以使用System.Collections.Specialized.StringCollection
類型來保存 ComboBox 項目。 首先在設置設計器中創建這種類型的變量,例如 CboItems。
閱讀項目:
if (Properties.Settings.Default.CboItems != null)
comboBox1.Items.AddRange(Properties.Settings.Default.CboItems.Cast<string>().ToArray());
要保存項目:
var items = new System.Collections.Specialized.StringCollection();
items.AddRange(comboBox1.Items.Cast<string>().ToArray());
Properties.Settings.Default.CboItems = items;
Properties.Settings.Default.Save();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.