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
|
请发表评论