[转]ASP.NET 2.0中TreeView递归遍历及设置结点展开算法

一、入口参数:
tnode:TreeNode  //树的根节点
condition:string //展开条件

二、返回值:
true:已找到符合条件的结点
false:未找到符合条件的结点

三、基本思想:
1.若tnode无子树,则结束,返回false。
2.展开当前节点tnode。
3.搜索是否有要显示的子结点,是则返回true,否则,返回false。//这里进行递归
4.若返回false,则收缩当前结点。

四、代码实现:
private bool expCollByUrl(TreeNode tnode, string url) //用当前的Url作为参数
    {
        bool canExp = false;  //记录是否已经找到要展开的结点
        if (tnode.ChildNodes.Count == 0) return false;   //递归结束条件
        tnode.Expand();
        foreach (TreeNode cnode in tnode.ChildNodes)
        {
            if (cnode.NavigateUrl.ToLower() == url.ToLower())
            {
                cnode.Selected = true;
                cnode.Expand();
                canExp = true;
                break;
            }
            if (expCollByUrl(cnode, url)) { canExp = true; break; }  //这里进行递归
        }
        if (!canExp)
        {
            tnode.Collapse();
        }
        return canExp;
    }

posted @ 2008-08-22 09:19  jamin  阅读(753)  评论(0编辑  收藏  举报