1

I need to save and load a listview / observablecollection when I open and close the app.

I have search around here and other places, and tried some things, but nothing seems to work.

I've pasted the code I found, that I thought did the trick. maybe it does with some changes.

//This one is for adding items, and it works fine.

try
                {

                    Tanknings.Add(new Tankning { Date = Dato.Date.ToString("dd-MM-yyyy"),
                        KmTaeller = KmTaeller.Text,
                        LiterTanket = Math.Round(Convert.ToDouble(LiterTanket.Text), 2).ToString(),
                        Pris = Math.Round(Convert.ToDouble(Pris.Text), 2).ToString(),
                        KmKoert = (Convert.ToInt32(KmTaeller.Text) - Convert.ToInt32(AktuelKmTaeller.Text)).ToString(),
                        PrisPrLiter = Math.Round((Convert.ToDouble(Pris.Text) / Convert.ToDouble(LiterTanket.Text)), 2).ToString(),
                        KmPrLiter = Math.Round(((Convert.ToDouble(KmTaeller.Text) - (Convert.ToDouble(AktuelKmTaeller.Text))) / Convert.ToDouble(LiterTanket.Text)), 2).ToString() });
            }
                catch
                {
                }

//This i what i tried to save and load the items.

private async void saveTankninger()
        {
            XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Tankning>));

            using (StreamWriter wr = new StreamWriter("Files/Tankninger.xml"))
            {
                xs.Serialize(wr, Tanknings);
            }

            /* Firstly we will use StorageFolder class from the Windows.Storage namespace
            to get path to the LocalFolder for our application: */
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            /* Then we need to have reference to the file where we can store notes:
            Note that if file exists we do not want to create another one: */
            StorageFile notesFile = await storageFolder.CreateFileAsync("Tankninger.txt", CreationCollisionOption.OpenIfExists);

            // Now we want to serialize list with the notes to save it in the JSON format ine the file:
            var serializedNotesList = JsonConvert.SerializeObject(Tanknings);

            // Last step is to write serialized list with notes to the text file:
            await FileIO.WriteTextAsync(notesFile, serializedNotesList);
        }

        private async void loadTankninger()
        {
            /* Firstly we will use StorageFolder class from the Windows.Storage namespace
            to get path to the LocalFolder for our application: */
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            /* Then we need to have reference to the file where we can store notes:
            Note that if file exists we do not want to create another one: */
            StorageFile notesFile = await storageFolder.CreateFileAsync("Tankninger.txt", CreationCollisionOption.OpenIfExists);

            // Read serialized notes list from the file:
            string serializedNotesList = await FileIO.ReadTextAsync(notesFile);

            // Deserialize JSON list to the ObservableCollection:
            if (serializedNotesList != null)
            {
                Tanknings = JsonConvert.DeserializeObject<ObservableCollection<Tankning>>(serializedNotesList);
                tankningTable.ItemsSource = Tanknings;
            }
        }
Vytautas Plečkaitis
  • 851
  • 1
  • 13
  • 19
TheisTN
  • 23
  • 6

1 Answers1

0

Assuming that you are using newtonsoft JSON library and have populated List

Serialise :

using Newtonsoft.Json;

List<Class_name> aList = getListFromSomehwere();
string json = JsonConvert.SerializeObject(aList);
// Do whatever you want with string, e.g. save to file

Deserialise :

using Newtonsoft.Json;
string json = ReadFile(); // Your function to read all text from file

List<Class_name> aList = (JsonConvert.DeserializeObject<IEnumerable<Class_name>>(json)).ToList();
// Do whatever you want with this list

To save on close - just add event to your application closing event, serialise list and save it to file.

To open on load - add window_loaded event (or form shown or whatever you prefer), read all file, deserialise json. There's many ways to approach this and it is up to you to decide what you want to do.

Edit : JSON.NET DeserializeObject to List of Objects might help

Vytautas Plečkaitis
  • 851
  • 1
  • 13
  • 19
  • It is almost working now. I can Save one item, and load it back in. but it wont add any new to the Listview. But it adds the "next one" to the .txt file, so next time I open it, it that one that shows. – TheisTN Jul 13 '19 at 16:19