1
votes

enter code hereI have got isolated storage working but it's only storing one item.

I want to be able to store a list of favourites for the user to use in a list.

At the moment, i can store loads of stops, but when i open the application again, it only rememers the last item. and deletes the rest.

private void ApplicationBarFavouriteButton_Click(object sender, EventArgs e)

    {
        IsolatedStorageSettings  settings = IsolatedStorageSettings.ApplicationSettings;
        // txtInput is a TextBox defined in XAML.
        if (!settings.Contains("userData"))
        {
            settings.Add("userData", busStopName.Text);
        }
        else
        {
            settings["userData"] = busStopName.Text;
        }
        settings.Save();
        MessageBox.Show("Bus Stop was added to your favourites");
    }

then for displaying the list

 if (IsolatedStorageSettings.ApplicationSettings.Contains("userData"))
        {
            listFav.Items.Add(IsolatedStorageSettings.ApplicationSettings["userData"] as string); 

        }

EDIT:

 private void ApplicationBarFavouriteButton_Click(object sender, EventArgs e)

    {


       IsolatedStorageSettings  settings = IsolatedStorageSettings.ApplicationSettings;


    List<string> favourites = settings["favourites"] as List<string>;

       if (favourites == null)
       {
           favourites = new List<string>();
           settings.Add("favourites", favourites);
       }

       favourites.Add(busStopName.Text);

       settings["favourites"] = favourites;
}

displaying the data

 if (IsolatedStorageSettings.ApplicationSettings.Contains("favourites"))
        {
            listFav.Items.Add(IsolatedStorageSettings.ApplicationSettings["favourites"] as List<string>);
        }
2

2 Answers

3
votes

You can access your settings like you would a hash/dictionary. So if your store information in settings["bob"], you will overwrite settings["bob"] when you next store something with the same key ("bob"). In your case, you're using the key "userData", every time you use settings["userData"] = "something";, you're overwriting what is stored in that key in the settings.

You could use something like the following (I've renamed your setting to "favourites" so that it is more descriptive of it's contents):

List<string> favourites;

settings.TryGetValue("favourites", out favourites);

if (favourites == null)
{
    favourites = new List<string>();
    settings.Add("favourites", favourites);
}

favourites.Add(busStopName.Text);

settings["favourites"] = favourites;

and for displaying it:

if (IsolatedStorageSettings.ApplicationSettings.Contains("userData"))
{
    listFav.Items.AddRange(IsolatedStorageSettings.ApplicationSettings["favourites"] as List<string>);
}
0
votes

You probably need to store a generic List of type string of Stops and then read this List from the ApplicationSettings, add a new stop to the List and then store the List back to the ApplicationSettings.