TreeView控件应用(包含递归调用)

简介: using System; using System.Windows.Forms; namespace TreeView控件 {     public partial class Form1 : Form     {         public ...

using System;
using System.Windows.Forms;

namespace TreeView控件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            //每一个节点都是一个TreeNode的一个对象
            TreeNode nodeChina = new TreeNode();
            nodeChina.Text = "中国";
            nodeChina.Tag = "好人";
            nodeChina.Nodes.Add("江苏");
            TreeNode nodeBeiJing = new TreeNode("北京");
            nodeChina.Nodes.Add(nodeBeiJing);
            treeView1.Nodes.Add(nodeChina);

            TreeNode nodeJapan = new TreeNode();
            nodeJapan.Text = "日本";
            //把节点的tag属性指向一个对象
            nodeJapan.Tag = "剑人";
            nodeJapan.Nodes.Add("东京");
            treeView1.Nodes.Add(nodeJapan);

            //通过创建对象来创建节点,将节点的tag属性指向这个对象
            Area shanghai = new Area("上海");
            shanghai.Boss = "上海市长";
            TreeNode nodeShanghai = new TreeNode();
            nodeChina.Nodes.Add(nodeShanghai);
            nodeShanghai.Text = shanghai.Name;
            nodeShanghai.Tag = shanghai;
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //MessageBox.Show(e.Node.Tag.ToString());
            MessageBox.Show(e.Node.Text);
        }

        //用递归遍历树
        private void button2_Click(object sender, EventArgs e)
        {
            foreach (TreeNode node in treeView1.Nodes)
            {
                DisplayNode(node);
            }
        }
        private void DisplayNode(TreeNode node)
        {
            textBox1.AppendText(node.Text + "\r\n");
            if (node.Nodes.Count>0)
            {
                foreach (TreeNode childNode in node.Nodes)
                {
                    DisplayNode(childNode);
                }
            }
        }

    }
}

相关文章
|
区块链
18 MFC - 树控件 CTreeCtrl
18 MFC - 树控件 CTreeCtrl
48 0
|
C++
Qt动态添加控件并设置大小位置等属性
Qt动态添加控件并设置大小位置等属性
1025 0
|
C#
WPF TreeView 选择事件执行两次,获取TreeView的父节点的解决方法
1.TreeView选择事件执行两次 Very often, we need to execute some code in SelectedItemChanged depending on the selected TreeViewItem.
1161 0
|
C#
WPF—TreeView无限极绑定集合形成树结构
原文:WPF—TreeView无限极绑定集合形成树结构 1.如图所示:绑定树效果图   2.前台Xaml代码:                                                                                          ...
1282 0
|
C#
WPF查找子控件和父控件方法
原文:WPF查找子控件和父控件方法 public List GetChildObjects(DependencyObject obj, string name) where T : FrameworkElement { Dependen...
1411 0
|
C#
【C#】wpf查找父子节点
原文:【C#】wpf查找父子节点 using System; using System.Collections.Generic; using System.
867 0