privatevoid 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);
}
}
![](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// Call the procedure using the TreeView.
privatevoid CallRecursive(TreeView treeView)
{
// Print each node recursively.
TreeNodeCollection nodes= treeView.Nodes;
foreach (TreeNode nin nodes)
{
PrintRecursive(n);
}
}
然后要说明的是一下TreeView类和TreeNode类之间的关系:TreeView类中有个只读属性是Nodes,它是属于TreeNodeCollection类型的,而对于一个TreeView它的Nodes属性就是返回treeView根结点的集合。
然后就是我的递归遍历查找一个树节点的方法(由于程序需要我是根据树节点的ImageIndex属性查找的):
private TreeNode FindTreeNode(int imageIndex, TreeNode tnParent)
{
if (tnParent== null)
returnnull;
if (tnParent.ImageIndex== imageIndex)
return tnParent;
TreeNode tnRet =null;
foreach (TreeNode tnin 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 nin 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;
}