C# 遍历treeview

 

1. 设置全部选中或全部选中,设置参数flag(true/false)

       private void checkSubNodes(TreeNode treeNode,bool flag)
        {
            treeNode.Checked = flag;
             foreach (TreeNode tn in treeNode.Nodes)
            {
                PrintRecursive(tn,flag);
            }
        }

       private void CheckTreeview(TreeView treeView,bool flag)
        {

            TreeNodeCollection nodes = treeView.Nodes;
            foreach (TreeNode n in nodes)
            {
                checkSubNodes(n,flag);
            }
        }

 

2.选中状态的改变:只要选中一个子节点,其父节点就是选中的

     我的项目里同时在数据区添加了点数据

     private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.Unknown)
            {
                CheckAllChildNodes(e.Node, e.Node.Checked);

                //选中父节点
                bool bol = e.Node.Checked;
                if (e.Node.Parent != null)
                {
                   
                    for (int i = 0; i < e.Node.Parent.Nodes.Count; i++)
                    {
                        if (e.Node.Parent.Nodes[i].Checked)
                            bol = true;
                    }
                    e.Node.Parent.Checked = bol;
                    e.Node.Parent.Tag = 1;
                }
            }
        }

 

      //选中子节点
        public void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                if (nodeChecked)
                {
                    node.Tag = 1;
                }
                else
                {
                    node.Tag = 0;
                }
                node.Checked = nodeChecked;
                if (node.Nodes.Count > 0)
                {
                    this.CheckAllChildNodes(node, nodeChecked);
                }
            }
        }

 

3.设置指定的节点为选中状态

      private void SelectSubNodes(TreeNode treeNode, string nodeName)
        {
            if (treeNode.Text.Equals(nodeName))
            {
                treeNode.Checked = true;
            }
                      foreach (TreeNode tn in treeNode.Nodes)
            {
                SelectSubNodes(tn, nodeName);
            }
        }

        private void SelectNodes(TreeView treeView, string nodeName)
        {
            TreeNodeCollection nodes = treeView.Nodes;
            foreach (TreeNode n in nodes)
            {
                SelectSubNodes(n, nodeName);
            }
        }

你可能感兴趣的:(C#,编程)