1
votes

I use a treeview control in my windows application. In this application, there is a button that adds several nodes (root node & child node). Now I want to save this structure and use it when I open the application again.

How do I can do this?

1

1 Answers

0
votes

You need to do following things

1- Serilize your tree structor using BinaryFormatter , as a starting point see below

private Byte[] SerilizeQueryFilters()
    {
        BinaryFormatter bf = new BinaryFormatter();

        TreeNodeCollection tnc = treeView1.Nodes;

        List<TreeNode> list = new List<TreeNode>();
        list.Add(treeView1.Nodes[0]);


        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, list);
            return ms.GetBuffer();

        }


    }

2- Once you got the Byte array , you can either save it to the database or in a file.

3- When you want to re-create the tree , you need to deserilize your saved data if it is in the databse , read the actual bytes and strore in a byte[] array or if it is in the file load the file and read all bytes into a Byte Array.

4- When you got the actual bytes , you can deserielize as per below code

 private void DeSerilizeQueryFilters(byte[] items)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<TreeNode> _list = new List<TreeNode>();

        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(items, 0, items.Length);
                ms.Position = 0;

                _list = bf.Deserialize(ms) as List<TreeNode>;



            }


        }
        catch (Exception ex)
        {
        }




    }

here you can see the _list will contain the actual root node which was serilized earlier , now you got the data , you can re-construct your tree.