winform如何保持TreeView节点展开和折叠的状态

转载:http://blog.sina.com.cn/s/blog_6abcacf5010138q5.html

winform如何保持TreeView节点展开和折叠的状态
 private Hashtable NodesStatus = new Hashtable();
        private string SelectNodeFullPath = string.Empty;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="nodes"></param>
        private void GetTreeNodesStatus(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.IsExpanded)
                {
                    NodesStatus[node.FullPath] = true;
                }
                else
                {
                    NodesStatus.Remove(node.FullPath);
                }
                if (node.IsSelected)
                {
                    SelectNodeFullPath = node.FullPath;
                }
                GetTreeNodesStatus(node.Nodes);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="nodes"></param>
        private void SetTreeNodesStatus(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                if (NodesStatus[node.FullPath] != null)
                {
                    node.Expand();
                }
                if (node.FullPath == SelectNodeFullPath)
                {
                    this.tvAuthFuction.SelectedNode = node;
                }
                SetTreeNodesStatus(node.Nodes);
            }
        }
    }
View Code

调用:

然后在给TreeView添加Nodes的前面和后面分别添加上这两个函数,例如TreeView类的实例tv,就可以使用
GetTreeNodesStatus(tv.Nodes);
//更新TreeView函数
SetTreeNodesStatus(tv.Nodes);
这样就能实现TreeView的状态保持了

winform如何保持TreeView节点展开和折叠的状态

上一篇:详解C#事件机制


下一篇:C#中sizeof的用法实例分析