AaronParkes
AaronParkes

Reputation: 311

Creating a new list Item from a string

I have a program with a combo box, a list for that box and a string.

The string is created from user input via a text box and is saved each time the program closes. So if I type "Input Text" then close and open the program the combo box will have a list containing 1 string which displays "Input Text"

The issue is I want to keep adding to the list with new information but at the moment its just constantly overriding what I put in last time.

How do I add to my list with a new item each time the string is different?

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

Upvotes: 0

Views: 87

Answers (2)

Gilad Green
Gilad Green

Reputation: 37299

instead of overriding the text in the file do:

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

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

And then when reading it:

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

Upvotes: 1

Jason Evans
Jason Evans

Reputation: 29186

The problem is that you are saving only the selected item text in your settings, not all the items in the combo box.

I suggest to get all the items in the combo first and put them in a comma delimited string.

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

Upvotes: 1

Related Questions