2016-08-19 5 views
0

私は、コンボボックス、そのボックスのリスト、および文字列を持つプログラムを持っています。新しいリストアイテムを文字列から作成する

文字列は、ユーザー入力からテキストボックスを使用して作成され、プログラムが終了するたびに保存されます。 "Input Text"と入力してプログラムを閉じて開くと、コンボボックスに "Input Text"と表示される1文字列のリストが表示されます。

問題は新しい情報でリストに追加し続けたいのですが私が最後に入れたものを絶えず上書きする瞬間です。

文字列が異なるたびに新しいアイテムで自分のリストに追加するにはどうすればよいですか?

private void Form1_Load(object sender, EventArgs e) 
{ 
    //Load Settings 
    saveLocationTextBox.Text = MySettings.Default["SaveSaveLocationText"].ToString(); 

    List<string> list = new List<string>(); 
    list.Add(saveLocationTextBox.Text); 

    comboBox.DataSource = list; 
} 

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    //Save User Input 
    MySettings.Default["SaveSaveLocationText"] = saveLocationTextBox.Text; 
    MySettings.Default.Save(); 
} 
+1

あなたがデータソースとしてコンボボックスに割り当てられた文字列の既存のリストを保存する必要が – Dan

+1

別のファイルにリストを入れてみてください、と 'にForm1_Load'するのではなく、文字列の保存されたリストに新しい文字列を追加する必要があります新しいリストを作成してそのリストに追加するよりも新しいリストを最初から作成し、その中に新しい文字列を追加するたびに。 – biseibutsu

答えて

1

問題は、あなたが唯一の選択した項目のテキストを保存しているということですあなたの設定ではなく、コンボボックス内のすべての項目。

コンボのすべての項目を最初に取得し、コンマで区切った文字列にすることをお勧めします。

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    //Save User Input 
    string[] itemsToStore = new string[comboBox.Items.Count]; 

    for (int i = 0; i < comboBox.Items.Count; i++) 
    { 
     itemsToStore[i] = comboBox.GetItemText(comboBox.Items[i]); 
    } 

    MySettings.Default["SaveSaveLocationText"] = saveLocationTextBox.Text; 
    MySettings.Default["SaveSaveLocationItems"] = string.Join(",", itemsToStore); 
    MySettings.Default.Save(); 
} 

private void Form1_Load(object sender, EventArgs e) 
{ 
    //Load Settings 
    saveLocationTextBox.Text = MySettings.Default["SaveSaveLocationText"].ToString(); 

    string listItems = MySettings.Default["SaveSaveLocationItems"].ToString(); 

    List<string> list = new List<string>(); 
    list.AddRange(listItems.Split(',')); 

    comboBox.DataSource = list; 
} 
1

の代わりに、ファイル内のテキストを上書き行います

var items = comboBox.Items.Select(item => comboBox.GetItemText(item)).ToList(); 
items.Add(saveLocationTextBox.Text); 

MySettings.Default["SaveSaveLocationText"] = string.Join(";", items); 

そして、それを読んだときに:

var text = MySettings.Default["SaveSaveLocationText"].ToString(); 
comboBox.DataSource = text.Split(';').ToList(); 
+0

@AaronParkes - 問題を解決できましたか? –

関連する問題