Here you want to use multi different types of the tree node such as Child1TreeNode, Child2TreeNode, so you need a way to determine which object should be created when the treenode is rebuilt on postback. And the ViewState comes to mind as an option when you can use it to persist the node type in order to recreate the tree node. However, when you create a tree node in the overriden CreateNode method in the custom treeview, the ViewState of the tree node has not been loaded yet, so you will do that as soon as the ViewState is loaded. In the CreateNode, you simply return the base class of your two node types, say ChildTreeNode, and you will replace this base node with the exact type after the node type is determined. Below is the sample code to demonstrate this thing:
public class ExTreeView : TreeView
{
protected override TreeNode CreateNode()
{
return new ChildTreeNode(this);
}
}
public class ChildTreeNode : TreeNode
{
public ChildTreeNode() { }
public ChildTreeNode(string nodeType) { m\_NodeType = nodeType; }
public ChildTreeNode(ExTreeView owner) { this.m\_Owner = owner; }
private ExTreeView m\_Owner;
internal ExTreeView Owner { get { return m\_Owner; } }
private string m\_NodeType;
internal string NodeType
{
get { return m\_NodeType; }
set { m\_NodeType = value; }
}
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
return new Pair(baseState, NodeType);
}
protected override void LoadViewState(object savedState)
{
Pair p = savedState as Pair;
base.LoadViewState(p.First);
NodeType = p.Second as string;
//The node type is hard coded for the sake of simplicity.
TreeNode newNode;
if (NodeType == "Child1TreeNode") { newNode = new Child1TreeNode(); }
else if (NodeType == "Child2TreeNode") { newNode = new Child2TreeNode(); }
else { newNode = new TreeNode(); }
newNode.Text = this.Text;
newNode.Value = this.Value;
ReplaceCurrentNode(this, newNode);
}