天道酬勤

博观而约取,厚积而薄发!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# TreeView递归遍历方法

Posted on 2010-04-29 18:58  Happy Coding  阅读(2918)  评论(0编辑  收藏  举报
1 以下是经测试无错的,呵呵,之前在网上看到个代码多多少少有点问题。递归遍历以深度优先,算不得效率高的东西,
  不过要是树中的项目不是太多,使用上一定是没问题的。到时候有找到效率更好的方法再发上来

2  /// <summary>
3 /// 查找TreeView控件下是否有指定值的节点
4 /// </summary>
5 /// <param name="tvControl">TreeView控件</param>
6 /// <param name="strValue">指定节点值</param>
7 /// <returns></returns>
8   public static TreeNode FindNode(TreeView tvControl,string strValue)
9 {
10 TreeNode tnRet = null;
11
12 foreach (TreeNode tn in tvControl.Nodes)
13 {
14
15 tnRet = FindNode(tn, strValue);
16
17 if (tnRet != null) break;
18
19 }
20
21 return tnRet;
22
23 }
24
25 /// <summary>
26 /// 查找当前节点下是否有指定值的节点
27 /// </summary>
28 /// <param name="tnParent">当前节点</param>
29 /// <param name="strValue">指定节点值</param>
30 /// <returns>TreeNode</returns>
31 public static TreeNode FindNode(TreeNode tnParent, string strValue)
32 {
33 if (tnParent == null) return null;
34
35 if (tnParent.Value == strValue) return tnParent;
36
37 TreeNode tnRet = null;
38 TreeNode tnTemp = null;
39
40 foreach (TreeNode tn in tnParent.ChildNodes)
41 {
42
43 tnTemp = FindNode(tn, strValue);
44
45 if (tnTemp != null && tnTemp.Value == strValue)
46 {
47 tnRet = tnTemp;
48 break;
49 }
50
51 }
52
53 return tnRet;
54
55 }
56
57 /// <summary>
58 /// 查找TreeView控件下是否有指定值的节点
59 /// </summary>
60 /// <param name="tvControl">TreeView控件</param>
61 /// <param name="strValue">指定节点值</param>
62 /// <returns></returns>
63 public static TreeNode FindNode(TreeView tvControl,string strValue)
64 {
65 TreeNode tnRet = null;
66
67 foreach (TreeNode tn in tvControl.Nodes)
68 {
69
70 tnRet = FindNode(tn, strValue);
71
72 if (tnRet != null) break;
73
74 }
75
76 return tnRet;
77
78 }
79
80 /// <summary>
81 /// 查找当前节点下是否有指定值的节点
82 /// </summary>
83 /// <param name="tnParent">当前节点</param>
84 /// <param name="strValue">指定节点值</param>
85 /// <returns>TreeNode</returns>
86 public static TreeNode FindNode(TreeNode tnParent, string strValue)
87 {
88 if (tnParent == null) return null;
89
90 if (tnParent.Value == strValue) return tnParent;
91
92 TreeNode tnRet = null;
93 TreeNode tnTemp = null;
94
95 foreach (TreeNode tn in tnParent.ChildNodes)
96 {
97
98 tnTemp = FindNode(tn, strValue);
99
100 if (tnTemp != null && tnTemp.Value == strValue)
101 {
102 tnRet = tnTemp;
103 break;
104 }
105
106 }
107
108 return tnRet;
109
110 }
111