ASP.NET Treeview Clone extension method

So you’ve notice yourself that Treeview since .NET 2.0 is missing the Clone method?? I’m sure you did when you attempted to copy nodes from one TreeView to another and found out that actually every time is was actually Moving them. Well imagine the following scenario: You have to keep 2 Treeviews syncronized, every time user checks/unchecks a node (leaf or folder type). The TreeView’s have been populated from SharePoint lists (list items have been prior prepared with multiple GroupBy LINQ clauses after retrieving with SPQuery, i’ll show you how i did it).
So obviously i had various options, but the most usefull seemed to me, as working in .NET 3.5 environment to define an extension method for it. To have it complete, I decided to make it Clone nodes in the direction caller would like (actually the scenario was requirying it):
So first we have to define a Static class as required by the extension methods, followed by adding one enum CloneDirection (see code):

public static class WebControlsExtensions

public enum CloneDirection { Down, Up, Siblings };
/// <summary>
Clones a node and all child nodes
/// <param name="clonedNode">Node to be cloned
/// <returns>Cloned version of the TreeNode
/// <remarks>This method only.
public static TreeNode Clone(this TreeNode clonedNode, bool recursiveClone, CloneDirection
TreeNode newClonedNode = new TreeNode();
newClonedNode.Text = clonedNode.Text;
newClonedNode.Value = clonedNode.Value;
newClonedNode.Checked = clonedNode.Checked;
//Add here other properties you might need to clone.
switch (directionToClone)
case CloneDirection.Up:if (clonedNode.Parent != null) //are we already on the root node?
if (recursiveClone) //we go all the way up.
TreeNode newParentNode = clonedNode.Parent.Clone(recursiveClone, CloneDirection.Up);newParentNode.ChildNodes.Add(newClonedNode); //add this node to its NEW parent.
return newParentNode;
case CloneDirection.Down:
foreach (TreeNode childNode in clonedNode.ChildNodes)
if (recursiveClone)
newClonedNode.ChildNodes.Add(childNode.Clone(recursiveClone, directionToClone));}break;
case CloneDirection.Siblings:
//nothing here so far
return newClonedNode;
That’s it, give it a try…and let me know what you think.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s