Code Listing for 2005_10_20 (C#)
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
// Recursively searches the tree for all nodes at a given depth
// and adds them to a list of TreeNodes
private void FindNodesAtDepth(TreeNodeCollection collection,
int targetDepth,
List<TreeNode> targetNodes)
{
foreach (TreeNode node in collection)
{
if (node.Depth == targetDepth)
{
targetNodes.Add(node);
}
else if (node.Depth < targetDepth)
{
FindNodesAtDepth(node.ChildNodes, targetDepth, targetNodes);
}
}
}
// Recursively creates a clone of a given TreeNode Hierarchy
private void CloneTreeNodeHierarchyRecursive(TreeNodeCollection inCollection,
TreeNodeCollection outCollection)
{
foreach (TreeNode node in inCollection)
{
TreeNode clonedNode = ((ICloneable)node).Clone() as TreeNode;
outCollection.Add(clonedNode);
if (node.ChildNodes.Count > 0)
{
CloneTreeNodeHierarchyRecursive(node.ChildNodes, clonedNode.ChildNodes);
}
}
}
protected void TreeView_DataBound(object sender, EventArgs e)
{
TreeView Tree = sender as TreeView;
// Only prune the tree if a node is selected
if(Tree.SelectedNode != null)
{
List<TreeNode> childNodes = new List<TreeNode>();
TreeNodeCollection childNodeCollection = new TreeNodeCollection();
FindNodesAtDepth(Tree.Nodes, Tree.SelectedNode.Depth, childNodes);
// copy from List<TreeNode> to TreeNodeCollection
foreach (TreeNode node in childNodes)
{
childNodeCollection.Add(node);
}
// clear the Tree's nodes and add the nodes we found
Tree.Nodes.Clear();
CloneTreeNodeHierarchyRecursive(childNodeCollection, Tree.Nodes);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" OnDataBound="TreeView_DataBound">
</asp:TreeView>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
</div>
</form>
</body>
</html>