1、 节点查找
以节点的名称准确匹配,查找递归函数如下:
public TreeNode RuleFind(string strFind)
{
TreeNode tnRet = null;
foreach(TreeNode tn in TreeView1.Nodes) )//Treeview1:查找树
{
tnRet = RuleFindNode(tn, strFind.Trim());
if (tnRet != null)
break;
}
return tnRet;
}
private TreeNode RuleFindNode(TreeNode tnParent, string strValue)//递归查找树型节点
{
if (tnParent == null) return null;
if (tnParent.Text.Trim() == strValue)
{
ExpandParent(tnParent); )//调用节点展开函数
tnParent.Selected = true;
return tnParent;
}
TreeNode tnRet = null;
foreach (TreeNode tn in tnParent.ChildNodes)// tnParent.Nodes)
{
tnRet = RuleFindNode(tn, strValue);
if (tnRet != null) break;
}
return tnRet;
}
另外为了使操作者一目了然,还需要节点展开函数(当然,如果树本身是展开的就无所谓了):
protected void ExpandParent(TreeNode node)//递归展开父节点
{
if (node.Parent != null)
{
node.Parent.Expanded = true;
node.Parent.Expand();
ExpandParent(node.Parent);
}
}
2、 节点添加
public void AddNewNode(TreeNode nodeNew)
{
// TreeNode nodeNew = new TreeNode("NewNode");// 新建节点对象
nodeNew.Selected = true;
if (TreeView1.SelectedNode == null)
return;
switch (TreeView1.SelectedNode.Depth) //节点深度选择
{
case 0:
case 1:
case 6:
Response.Write("Not allow to add");
break;
default:
TreeView1.SelectedNode.ChildNodes. Add(nodeNew);
break;
}
}
从本函数看来,此树除了0、1 、6外都是可添加的节点。
3、 节点删除
public void RemoveNode(TreeNode node)
{
if (node == null)
return;
TreeNode parentNode = nodeNew.Parent;
parentNode.ChildNodes.Remove( node);
}