I need to extend the TreeNode class such that I can add custom properties to each node (seeing as WebForms TreeNode doesn't include the Tag property). So this is my CustomTreeNode:
public class CustomTreeNode : TreeNode
{
public CustomTreeNode()
{
}
public CustomTreeNode(int nodeId, string nodeType)
{
NodeId = nodeId;
NodeType = nodeType;
}
public string NodeType { get; set; }
public int NodeId { get; set; }
}
If I create a CustomTreeNode and add it to a TreeView:
CustomTreeNode node = new CustomTreeNode(1, "CustomType");
treeView.Nodes.Add(node);
I would then get a casting exception doing the following:
CustomTreeNode selectedNode = (CustomTreeNode)TreeView.SelectedNode;
because TreeView returns a TreeNode, not a CustomTreeNode.
I've done some reading, and it looks like I need to extend the TreeView class, and override the CreateNode() method to return CustomTreeNode instead of TreeNode. So I created this:
public class CustomTreeView : TreeView
{
protected override TreeNode CreateNode()
{
return new CustomTreeNode();
}
}
The problem is however, CreateNode() doesn't take any arguments, so you have to have call the empty constructor for the CustomTreeNode class. So when I created my CustomTreeNode above, when I get it back from the CustomTreeView, the nodeId and nodeType values have been lost because the empty constructor returns a node without any values.
Any help much appreciated.
This is what I came up with (experts, any advice welcomed). Instantiate the
CustomTreeNode
s in your code behind and set the properties via setters. Modify yourCustomTreeNode
class to persist the values in ViewState. The node returned by your custom tree view'sCreateNode
will load the ViewState information.TreeNode class:
TreeView class:
Simple .aspx file (Assuming that your custom control is defined in an assembly "Foo" and a namespace "Bar":
CodeBehind: