HOW TO:逐一查看 Windows Form TreeView 控制項的所有節點
有時候這在檢查 Windows Form TreeView 控制項的每個節點,以便對節點值進行某些計算時非常有用。 這項作業可以利用逐一查看每個樹狀集合物件 (Collection) 中每個節點的遞迴程序 (C# 和 C++ 中為遞迴方法) 來完成。
樹狀檢視中的每個 TreeNode 物件都有屬性,您可以使用這些屬性來巡覽樹狀檢視:FirstNode、LastNode、NextNode、PrevNode 和 Parent。 Parent 屬性的值是目前節點的父節點。 如果有子節點時,目前節點的子節點將列於 Nodes 屬性中。 TreeView 控制項本身具有 TopNode 屬性,這是整個樹狀檢視的根 (Root) 節點。
若要逐一查看 TreeView 控制項的所有節點
建立測試每個節點的遞迴程序 (C# 和 C++ 中為遞迴方法)。
呼叫此程序。
下列範例顯示如何列印每個 TreeNode 物件的 Text 屬性:
Private Sub PrintRecursive(ByVal n As TreeNode) System.Diagnostics.Debug.WriteLine(n.Text) MessageBox.Show(n.Text) Dim aNode As TreeNode For Each aNode In n.Nodes PrintRecursive(aNode) Next End Sub ' Call the procedure using the top nodes of the treeview. Private Sub CallRecursive(ByVal aTreeView As TreeView) Dim n As TreeNode For Each n In aTreeView.Nodes PrintRecursive(n) Next End Sub
private void PrintRecursive(TreeNode treeNode) { // Print the node. System.Diagnostics.Debug.WriteLine(treeNode.Text); MessageBox.Show(treeNode.Text); // Print each node recursively. foreach (TreeNode tn in treeNode.Nodes) { PrintRecursive(tn); } } // Call the procedure using the TreeView. private void CallRecursive(TreeView treeView) { // Print each node recursively. TreeNodeCollection nodes = treeView.Nodes; foreach (TreeNode n in nodes) { PrintRecursive(n); } }
private void PrintRecursive(TreeNode treeNode) { // Print the node. System.Diagnostics.Debug.WriteLine(treeNode.get_Text()); MessageBox.Show(treeNode.get_Text()); for(int i = 0; i < treeNode.GetNodeCount(false); ++i) // Print each node recursively. { PrintRecursive(treeNode.get_Nodes().get_Item(i)); } } // Call the procedure using the TreeView. private void CallRecursive(TreeView treeView) { // Print each node recursively. TreeNodeCollection nodes = treeView.get_Nodes(); for(int i = 0; i < nodes.get_Count(); ++i) { PrintRecursive(nodes.get_Item(i)); } }
private: void PrintRecursive( TreeNode^ treeNode ) { // Print the node. System::Diagnostics::Debug::WriteLine( treeNode->Text ); MessageBox::Show( treeNode->Text ); // Print each node recursively. System::Collections::IEnumerator^ myNodes = (safe_cast<System::Collections::IEnumerable^>(treeNode->Nodes))->GetEnumerator(); try { while ( myNodes->MoveNext() ) { TreeNode^ tn = safe_cast<TreeNode^>(myNodes->Current); PrintRecursive( tn ); } } finally { IDisposable^ disposable = dynamic_cast<System::IDisposable^>(myNodes); if ( disposable != nullptr ) disposable->Dispose(); } } // Call the procedure using the TreeView. void CallRecursive( TreeView^ treeView ) { // Print each node recursively. TreeNodeCollection^ nodes = treeView->Nodes; System::Collections::IEnumerator^ myNodes = (safe_cast<System::Collections::IEnumerable^>(nodes))->GetEnumerator(); try { while ( myNodes->MoveNext() ) { TreeNode^ n = safe_cast<TreeNode^>(myNodes->Current); PrintRecursive( n ); } } finally { IDisposable^ disposable = dynamic_cast<System::IDisposable^>(myNodes); if ( disposable != nullptr ) disposable->Dispose(); } }