首先先看一段MSDN上的樣本程式:列印一個樹中所有節點名稱
MSDN上遍曆樹節點的樣本程式
1private void PrintRecursive(TreeNode treeNode)
2{
3 // Print the node.
4 System.Diagnostics.Debug.WriteLine(treeNode.Text);
5 MessageBox.Show(treeNode.Text);
6 // Print each node recursively.
7 foreach (TreeNode tn in treeNode.Nodes)
8 {
9 PrintRecursive(tn);
10 }
11}
12
13// Call the procedure using the TreeView.
14private void CallRecursive(TreeView treeView)
15{
16 // Print each node recursively.
17 TreeNodeCollection nodes = treeView.Nodes;
18 foreach (TreeNode n in nodes)
19 {
20 PrintRecursive(n);
21 }
22}
然後要說明的是一下TreeView類和TreeNode類之間的關係:TreeView類中有個唯讀屬性是Nodes,它是屬於TreeNodeCollection類型的,而對於一個TreeView它的Nodes屬性就是返回treeView根結點的集合。
然後就是我的遞迴遍曆尋找一個樹節點的方法(由於程式需要我是根據樹節點的ImageIndex屬性尋找的):
Code
private TreeNode FindTreeNode(int imageIndex, TreeNode tnParent)
{
if (tnParent == null)
return null;
if (tnParent.ImageIndex == imageIndex)
return tnParent;
TreeNode tnRet = null;
foreach (TreeNode tn in tnParent.Nodes)
{
tnRet = FindTreeNode(imageIndex, tn);
if (tnRet != null)
break;
}
return tnRet;
}
private TreeNode CallFindNode(int imageIndex, TreeView treeView)
{
TreeNodeCollection nodes = treeView.Nodes;
foreach (TreeNode n in nodes)
{
TreeNode temp = FindTreeNode(imageIndex, n);
if (temp != null)
return temp;
}
return null;
}
/// <summary>
/// 這個是一個點擊事件,其中改變了選中節點,
/// 改變選中節點的同時就觸發了selectedNodeChanged事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void myControlTransactions_AddCustomer(object sender, EventArgs e)
{
TreeNode temp = CallFindNode(3, treeView1);
if (temp != null)
treeView1.SelectedNode = temp;
}