<%@ Page Language="VB" %>
<!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 Sub FindNodesAtDepth(ByVal collection As TreeNodeCollection, _
ByVal targetDepth As Integer, _
ByVal targetNodes As Generic.List(Of TreeNode))
For Each node As TreeNode In collection
If node.Depth = targetDepth Then
targetNodes.Add(node)
ElseIf node.Depth < targetDepth Then
FindNodesAtDepth(node.ChildNodes, targetDepth, targetNodes)
End If
Next
End Sub
' Recursively creates a clone of a given TreeNode Hierarchy
Private Sub CloneTreeNodeHierarchyRecursive(ByVal inCollection As TreeNodeCollection, _
ByVal outCollection As TreeNodeCollection)
For Each node As TreeNode In inCollection
Dim clonedNode As TreeNode = CType(node, ICloneable).Clone()
outCollection.Add(clonedNode)
If node.ChildNodes.Count > 0 Then
CloneTreeNodeHierarchyRecursive(node.ChildNodes, clonedNode.ChildNodes)
End If
Next
End Sub
' Databound event handler for a TreeView
Protected Sub TreeView_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Tree As TreeView = sender
' Only prune the tree if a node is selected
If Tree.SelectedNode IsNot Nothing Then
Dim childNodes As New Generic.List(Of TreeNode)()
Dim childNodeCollection As New TreeNodeCollection()
FindNodesAtDepth(Tree.Nodes, Tree.SelectedNode.Depth, childNodes)
' Copy from List(of TreeNode) to TreeNodeCollection
For Each node As TreeNode In childNodes
childNodeCollection.Add(node)
Next
' Clear the TreeView nodes and add the nodes we found
Tree.Nodes.Clear()
CloneTreeNodeHierarchyRecursive(childNodeCollection, Tree.Nodes)
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Demo 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>