天天看點

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

                }

    }

}

本文轉自蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366788,如需轉載請自行聯系原作者

繼續閱讀