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

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

    }
}

你可能感兴趣的:(TreeView控件应用(包含递归调用))