0

I'm serializing a TreeNode using this function :

public static void SaveTree(TreeView tree, string filename)
{
    using (Stream file = File.Open(filename, FileMode.Create))
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(file, tree.Nodes.Cast<TreeNode>().ToList());
    }
}

when I deserialize using this function :

    public static TreeView LoadTree(string filename)
    {
        TreeView tree = new TreeView();
        using (Stream file = File.Open(filename, FileMode.Open))
        {
            BinaryFormatter bf = new BinaryFormatter();
            object obj = bf.Deserialize(file);

            TreeNode[] nodeList = (obj as IEnumerable<TreeNode>).ToArray();
            tree.Nodes.AddRange(nodeList);
        }
        return tree;
    }

I didn't get the nodes imageindex I get the value -1 for all nodes imageindex !
Why ?

Karam Najjar
  • 527
  • 5
  • 21
  • If you are using the code from [Saving content of a treeview to a file and load it later](http://stackoverflow.com/a/5868931/719186), it is appropriate to attribute the code you are using to the source. – LarsTech Apr 14 '14 at 21:00
  • @LarsTech , thank you for you note, but I didn't get these functions from here ! – Karam Najjar Apr 15 '14 at 11:52

2 Answers2

1

It seems the binary formatter is not working well. This should be because we are serializing a winforms control component. Here is an alternative I've found :

  • Create a new method that will see each node of your tree and set icons with your own conditions. What you can do is to create a custom tag class.

    public void SetIconsTreeNodes(IEnumerable<TreeNode> treeNodeCollection)
    {
        foreach (TreeNode node in treeNodeCollection)
        {
            // Set imageindex of node here with your own conditions
    
            TreeNode[] nodes = new TreeNode[node.Nodes.Count];
            node.Nodes.CopyTo(nodes, 0);
            SetIconsTreeNodes(nodes);
        }
    }
    
  • Modify the LoadTree method with this new method :

    public static void LoadTree(TreeView tree, string filename)
    {
        using (Stream file = File.Open(filename, FileMode.Open))
        {
            BinaryFormatter bf = new BinaryFormatter();
            object obj = bf.Deserialize(file);
            TreeNode[] nodeList = (obj as IEnumerable<TreeNode>).ToArray();
            SetIconsTreeNodes(nodeList);
            tree.Nodes.AddRange(nodeList);
        }
    }
    
Nat
  • 119
  • 5
0

Seems to be a bug.

If you set the Name property of each image in the ImageList, and then use the ImageKey and SelectedImageKey properties for the nodes instead of ImageIndex and SelectedImageIndex, the serialization then does work.

In your code though, don't forget to apply the ImageList control to the TreeView:

public static TreeView LoadTree(string filename, ImageList imageList) {
  TreeView tree = new TreeView();
  tree.ImageList = imageList;
  ...
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225