默认选中Treeview的某个节点修正方法

感谢High_Mount指出我的上一篇文章默认选中TreeView某个节点的方法中所写的选中Treeview某个节点的方法有错误,只能适用于少于三层的情况,下面我修改这个方法,使它能适用于任意多层。代码如下:

    /// <summary>
    
/// 选中treeview的某个节点,需要每个node的value不同
    
/// </summary>
    
/// <param name="sNodeValue"></param>

    private void selectNode(TreeView tv,string sNodeValue)
    
{
        
foreach (TreeNode tRoot in tv.Nodes)
        
{
            
if (tRoot.Value == sNodeValue)
            
{
                tRoot.Select();
            }

            
else
            
{
                
if (tRoot.ChildNodes != null)
                
{
                    
//foreach (TreeNode tChild in tRoot.ChildNodes)
                    
//{
                    
//    if (tChild.Value == sNodeValue)
                    
//        tChild.Select();
                    
//}
                    TreeNode tTmp = null;
                    tTmp 
= FindNode(tRoot, sNodeValue);
                    
if (tTmp != null)
                        tTmp.Select();
                }

            }

        }

    }


    
/// <summary>
    
/// 递归查找父节点
    
/// </summary>
    
/// <param name="tnParent">指定一个根节点,然后遍历它</param>
    
/// <param name="strValue">所要查找的节点的value</param>

    private TreeNode FindNode(TreeNode tnParent, string strValue)
    
{
        
if (tnParent == nullreturn null;
        
if (tnParent.Value == strValue) return tnParent;
        TreeNode tnRet 
= null;
        
foreach (TreeNode tn in tnParent.ChildNodes)
        
{
            tnRet 
= FindNode(tn, strValue);
            
if (tnRet != nullbreak;
        }

        
return tnRet;
    }
原文地址:https://www.cnblogs.com/vagerent/p/845691.html