I have a class that inherits from TreeNode, called ExtendedTreeNode. To add an object of this type to the treeview is not a problem. But how do I retrieve the object from the treeview?
I have tried this:
TreeNode node = tvManual.Find("path/to/node"); // tvManual is a treeview
return ((ExtendedTreeNode)node).Property;
But this doesn't work. I get this error: Unable to cast object of type 'System.Web.UI.WebControls.TreeNode' to type 'PCK_Web_new.Classes.ExtendedTreeNode'.
What do I have to do to make this work?
------------ SOLUTION -----------------
[Edit] My custom TreeNode class looks like this:
public class ExtendedTreeNode : TreeNode
{
private int _UniqueId;
public int UniqueId
{
set { _UniqueId = value; }
get { return _UniqueId; }
}
public ExtendedTreeNode()
{
}
}
And this way I add Nodes to my treeview:
ExtendedTreeNode TN2 = new ExtendedTreeNode();
TN2.Text = "<span class='Node'>" + doc.Title + "</span>";
TN2.Value = doc.ID.ToString();
TN2.NavigateUrl = "ViewDocument.aspx?id=" + doc.ID + "&doc=general&p=" + parent;
TN2.ImageUrl = "Graphics/algDoc.png";
TN2.ToolTip = doc.Title;
TN2.UniqueId = counter;
tvManual.FindNode(parent).ChildNodes.Add(TN2);
And this way I retrieve my ExtendedTreeNode object:
TreeNode node = tvManual.Find("path/to/node");
ExtendedTreeNode extNode = node as ExtendedTreeNode;
return extNode.UniqueId;
I am using .NET 3.5 SP1
I assume you're creating the nodes as
ExtendedTreeNode
s.I've noticed that the XxxView (ListView, TreeView, DataGridView) controls tend to clone things unexpectedly. Have you implemented
ICloneable.Clone ()
?That may work; TreeNode implements
Clone ()
virtually.I find it easier, though to implement extended properties using the Tag property of the treenode:
I strongly recommend against using
Clone ()
; it's a fragile pattern. Use the Tag property:You could try the following to get all nodes under your parent:
I found a Microsoft example for how to implement an ASP.NET
TreeView
with tags here.Some important steps that are necessary besides just subclassing
TreeNode
and adding aTag
property are:You must subclass
TreeView
and override theCreateNode
method:This prevents the
TreeView
from overwriting your new nodes withTreeNode
s instead of with your extended type of node.You will need to have that particular constructor available. (It seems to work using the default constructor, too, but there's a good chance there's a good reason why they used this one.)
In order to use the extended
TreeView
you will need aRegister
line like the following in your markup to import the type:You must also override
LoadViewState
andSaveViewState
in your inheritedTreeNode
class:This allows the
TreeView
to preserve the value of yourTag
properties between postbacks.