首页 > 代码库 > winform如何保持TreeView节点展开和折叠的状态

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

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

技术分享
 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节点展开和折叠的状态