C# 樹狀圖-找值,並展開節點!

  • 4132
  • 0

C# 樹狀圖-找值,並展開節點!

今天在寫「C# 樹狀圖」,

有二項要求-先找節點,並展開此節點(上層節點到此節點),

基本上找值有二種方法-「BY NAME/BY TEXT」,

以下為範例

 

        /// <summary>
        /// 呼叫找值
        /// </summary>         
        private void FindByText(string _Search, string _Model)
        {
            TreeNodeCollection nodes = TB.Nodes;
            foreach (TreeNode n in nodes)
            {
                if (_Model == "Name")
                {
                    FindRecursive(_Search, n);
                }
                if (_Model == "Text")
                {
                    FindRecursiveText(_Search, n);
                }
            }
        }

 

        /// <summary>
        /// 找代碼的節點
         /// </summary>
        /// <param name="treeNode"></param>
        private void FindRecursive(string _Search, TreeNode treeNode)
        {
            foreach (TreeNode tn in treeNode.Nodes)
            {
                if (tn.Name == _Search.ToString())
                {
                    tn.BackColor = Color.Yellow;
                    ShowNode(tn);//展開節點
                }
                else
                {
                    FindRecursive(_Search, tn);
                }
            }           

         }

 

        /// <summary>
        /// 找科目名稱的節點
         /// </summary>
        /// <param name="treeNode"></param>
        private void FindRecursiveText(string _Search, TreeNode treeNode)
        {
            foreach (TreeNode tn in treeNode.Nodes)
            {
                if (tn.Text == _Search.ToString())
                {
                    tn.BackColor = Color.Yellow;
                    ShowNode(tn);//展開節點
                }
                else
                {
                    FindRecursiveText(_Search, tn);
                }
            }
        }

 

        /// <summary>
        /// 展開節點,先展開第一層節點,所含的節點再全展開
        /// </summary>
        /// <param name="treeNode"></param>
        private void ShowNode(TreeNode treeNode)
        {
            TreeNode _stn;
            _stn = treeNode;
            if (_stn.Parent.Name.ToString() != "0")//不為最上層開頭點
            {                
                _stn.Parent.Expand();
                ShowNode(_stn.Parent);
            }
            else
            {
                _stn.Parent.Expand();//先展開第一層節點               
            }
        }

這是結果

tree

至於新增節點、刪除節點、節點變色就比較簡單,在此就不討論了!

 

自我LV~