I need to serialize items populated in a listview.

Can anyone provide me with some simple example how to do that.
No matter if it is binary or XML.

Recommended Answers

All 10 Replies

Are you wanting to serialize items included in the ListViewItem's .Tag property, or serialize the entire listview.items collection?

Are you wanting to serialize items included in the ListViewItem's .Tag property, or serialize the entire listview.items collection?

I really don't what's best. The listview items inputs comes from textboxes, and I have tried to approach serialization from textboxes as well. Maybe I need some array doing that. I can put up the entire testcode if you like.

Just take the item of listview in a array and the serialize it.

Here's my attempt doing a binary serialization. Together with a SaveFileDialog. Doesn't really work, but may show the way of thinking.

private void sparaSomToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // create dialog box enabling user to save file
            SaveFileDialog fileChooser = new SaveFileDialog();
            DialogResult result = fileChooser.ShowDialog();
            string fileName; // name of file to save data

            string NickName = this.lstListAnimals.Items[0].ToString();

            FileStream fs = new FileStream(@"C:\\savebinary.txt", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, NickName);
            fs.Close();

        }

I have added a array for the items, a file is created, but it not seems to contain all of the listview rows

ArrayList animals = new ArrayList();
            animals.Add(lstListAnimals.Items[0].ToString());
            animals.Add(lstListAnimals.Items[1].SubItems[1].ToString());
            animals.Add(lstListAnimals.Items[1].SubItems[2].ToString());
            animals.Add(lstListAnimals.Items[1].SubItems[3].ToString());
            animals.Add(lstListAnimals.Items[1].SubItems[4].ToString());
            animals.Add(lstListAnimals.Items[1].SubItems[5].ToString());

            FileStream fsWrite = File.Open(@"C:\\Info.txt", FileMode.Create, FileAccess.ReadWrite);
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(fsWrite, animals);
            fsWrite.Close();

What is the error coming?
What actually you want to do with data after serialization?

No errors, even if it's binary I can only find one post (row) in the txt file. I am missing something when trying to serialize all of the posts (rows) in listview.

The code is for my own training purpose, and later I want to deserialize back to the listview. And I also need to create a similar control for xml serializing.

I am still not sure this is the correct way saving listview items into a binary file. Something is saved, but probably not all of the listview items (rows).

private void sparaSomToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // create dialog box enabling user to save file
            SaveFileDialog DialogSave = new SaveFileDialog();
            DialogSave.DefaultExt = "txt";
            DialogSave.Filter = "Text file (*.txt)|*.txt|XML file (*.xml)|*.xml|All files (*.*)|*.*";
            DialogSave.RestoreDirectory = true;
            DialogSave.Title = "Save as";
            if (DialogSave.ShowDialog() == DialogResult.OK)
            {
                SaveFile(DialogSave.FileName);
            }

        }

        private void SaveFile(string fileName)
        {

            ArrayList animalList = new ArrayList();
            animalList.Add(this.lstListAnimals.Items[0].ToString());
            animalList.Add(this.lstListAnimals.Items[0].SubItems[1].ToString());
            animalList.Add(this.lstListAnimals.Items[0].SubItems[2].ToString());
            animalList.Add(this.lstListAnimals.Items[0].SubItems[3].ToString());
            animalList.Add(this.lstListAnimals.Items[0].SubItems[4].ToString());
            animalList.Add(this.lstListAnimals.Items[0].SubItems[5].ToString());

            FileStream fsWrite = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fsWrite, animalList);
            fsWrite.Close();
        }
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace daniweb
{
  public partial class frmListView : Form
  {
    public frmListView()
    {
      InitializeComponent();
    }

    private void frmListView_Load(object sender, EventArgs e)
    {
      //Gives us random data to play with
      listView1.BeginUpdate();
      SetupColumns();
      for (int i1 = 0; i1 < 10; i1++)
      {
        ListViewItem item = listView1.Items.Add(i1.ToString("F0"));
        for (int i2 = 0; i2 < 8; i2++)
        {
          item.SubItems.Add(i1.ToString("F0") + "|" + (i2+1).ToString("F0"));
        }
      }
      listView1.EndUpdate();
      listView1.Invalidate();
    }

    private void SetupColumns()
    {
      for (int i1 = 0; i1 < 9; i1++)
      {
        listView1.Columns.Add("Col" + i1.ToString("F0"));
      }
    }

    private void SaveListView()
    {
      List<SerizledListViewItem> lst = new List<SerizledListViewItem>();
      foreach (ListViewItem lvi in listView1.Items)
      {
        lst.Add(new SerizledListViewItem(lvi));
      }
      SerizledListViewItem.SaveCollection(@"C:\test.xml", lst);
    }

    private void LoadListView()
    {
      ClearListView();
      List<SerizledListViewItem> lst = SerizledListViewItem.FromFile(@"C:\test.xml");
      foreach (SerizledListViewItem serialItem in lst)
      {
        ListViewItem item = listView1.Items.Add(serialItem.Text);
        foreach (string serialSubItem in serialItem.SubItems)
        {
          item.SubItems.Add(serialSubItem);
        }
      }
    }

    private void ClearListView()
    {
      listView1.Clear();
      SetupColumns();
    }

    private void buttonSave_Click(object sender, EventArgs e)
    {
      SaveListView();
    }

    private void buttonClear_Click(object sender, EventArgs e)
    {
      ClearListView();
    }

    private void buttonLoad_Click(object sender, EventArgs e)
    {
      LoadListView();
    }
  }

  public sealed class SerizledListViewItem
  {
    private List<string> _subItems;

    public string Text { get; set; }
    public List<string> SubItems
    {
      get { return _subItems; }
      set
      {
        if (value == null) return;
        _subItems = value;
      }
    }
    public SerizledListViewItem()
    {
      _subItems = new List<string>();
    }
    public SerizledListViewItem(ListViewItem Item)
      : this()
    {
      this.Text = Item.Text;
      //Notice we start @ 1 here, the first item is a subitem
      for (int i1 = 1; i1 < Item.SubItems.Count; i1++)
      {
        this.SubItems.Add(Item.SubItems[i1].Text);
      }
    }
    public static List<SerizledListViewItem> FromFile(string FileName)
    {
      if (!File.Exists(FileName))
        throw new FileNotFoundException("Not found", FileName);

      XmlSerializer ser = new XmlSerializer(typeof(List<SerizledListViewItem>));
      using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(FileName)))
      {
        return (List<SerizledListViewItem>)ser.Deserialize(ms);
      }
    }
    public static void SaveCollection(string FileName, List<SerizledListViewItem> lst)
    {
      byte[] xmlData;
      XmlSerializer ser = new XmlSerializer(typeof(List<SerizledListViewItem>));

      using (MemoryStream ms = new MemoryStream())
      {
        ser.Serialize(ms, lst);
        ms.Position = 0;
        ms.Seek(0, SeekOrigin.Begin);
        xmlData = ms.ToArray();
      }
      if (File.Exists(FileName))
        File.Delete(FileName);
      File.WriteAllBytes(FileName, xmlData);
    }
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.