从树视图中保存节点 [英] Save nodes from a treeview

查看:30
本文介绍了从树视图中保存节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Windows 应用程序中使用树视图控件.在这个应用程序中,有一个按钮可以添加多个节点(根节点和子节点).现在我想保存这个结构并在我再次打开应用程序时使用它.

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.

我该怎么做?

推荐答案

你需要做以下事情

1- 使用 BinaryFormatter 序列化您的树结构体,作为起点,见下文

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- 获得 Byte 数组后,您可以将其保存到数据库或文件中.

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

3- 当您想重新创建树时,如果保存的数据在数据库中,则需要对保存的数据进行反序列化,读取实际字节并存储在 byte[] 数组中,或者如果它在文件中,则加载文件并将所有字节读入一个字节数组.

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- 当您获得实际字节数时,您可以按照以下代码进行反序列化

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)
        {
        }




    }

在这里你可以看到 _list 将包含之前被序列化的实际根节点,现在你得到了数据,你可以重新构建你的树.

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.

这篇关于从树视图中保存节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆