C#中遍历TreeView并查找和选定节点

本文介绍了一个使用C#实现的递归遍历TreeView及其节点的方法,并通过一个具体示例展示了如何查找指定ImageIndex的TreeNode。此外还提供了一个事件处理示例,用于改变TreeView的选中节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先先看一段MSDN上的示例程序:打印一个树中所有节点名称

ContractedBlock.gifExpandedBlockStart.gifMSDN上遍历树节点的示例程序
 1private void PrintRecursive(TreeNode treeNode)
 2ExpandedBlockStart.gifContractedBlock.gif{
 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)
 8ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 9        PrintRecursive(tn);
10    }

11}

12
13// Call the procedure using the TreeView.
14private void CallRecursive(TreeView treeView)
15ExpandedBlockStart.gifContractedBlock.gif{
16    // Print each node recursively.
17    TreeNodeCollection nodes = treeView.Nodes;
18    foreach (TreeNode n in nodes)
19ExpandedSubBlockStart.gifContractedSubBlock.gif    {
20        PrintRecursive(n);
21    }

22}

 

然后要说明的是一下TreeView类和TreeNode类之间的关系:TreeView类中有个只读属性是Nodes,它是属于TreeNodeCollection类型的,而对于一个TreeView它的Nodes属性就是返回treeView根结点的集合。

然后就是我的递归遍历查找一个树节点的方法(由于程序需要我是根据树节点的ImageIndex属性查找的):

ContractedBlock.gifExpandedBlockStart.gifCode
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;
}

转载于:https://www.cnblogs.com/CCBB/archive/2009/05/10/1453596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值