Adapt a tree model for Web Forms hierarchical data binding
Web Forms hierarchical controls need both a sequence of siblings and metadata for each node. IHierarchicalEnumerable supplies that sequence. IHierarchyData describes one node and its relationships.
Keep the adapter separate from the tree model. In particular, GetParent() must return an adapter for the parent, not cast a plain model to an interface it does not implement.
Add the model and adapter
For an existing .NET Framework 4.8.1 Web Forms application, add these classes to a compiled project file or, in a Web Site project, to App_Code/TreeModel.cs:
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
public sealed class DemoNode {
public string Id { get; set; }
public string Name { get; set; }
public DemoNode Parent { get; private set; }
public List<DemoNode> Children { get; } = new List<DemoNode>();
public void Add(DemoNode child) { child.Parent = this; Children.Add(child); }
}
public sealed class NodeSequence : IHierarchicalEnumerable {
private readonly IEnumerable<DemoNode> nodes;
public NodeSequence(IEnumerable<DemoNode> nodes) { this.nodes = nodes; }
public IEnumerator GetEnumerator() { return nodes.GetEnumerator(); }
public IHierarchyData GetHierarchyData(object item) { return new NodeData((DemoNode)item); }
}
public sealed class NodeData : IHierarchyData {
private readonly DemoNode node;
public NodeData(DemoNode node) { this.node = node; }
public bool HasChildren { get { return node.Children.Count != 0; } }
public object Item { get { return node; } }
public string Path { get { return node.Id; } }
public string Type { get { return "DemoNode"; } }
public IHierarchicalEnumerable GetChildren() { return new NodeSequence(node.Children); }
public IHierarchyData GetParent() { return node.Parent == null ? null : new NodeData(node.Parent); }
}
Each node ID must be unique across the tree. This bounded sample constructs the relationships directly. Importing a flat table additionally requires duplicate-ID, missing-parent and cycle validation.
Bind the TreeView
Place this control in the page's server form:
<asp:TreeView ID="Tree" runat="server">
<DataBindings>
<asp:TreeNodeBinding DataMember="DemoNode" TextField="Name" ValueField="Id" />
</DataBindings>
</asp:TreeView>
Use the following code in the page's initial load:
if (!IsPostBack) {
var root = new DemoNode { Id = "root", Name = "Reference" };
root.Add(new DemoNode { Id = "child", Name = "First note" });
Tree.DataSource = new NodeSequence(new[] { root });
Tree.DataBind();
Tree.ExpandAll();
}
Expect Reference with First note beneath it. The node's displayed name, stable ID, underlying item and parent now have distinct correct owners. Keep cycles out of the tree. Recursive data binding cannot safely consume a cyclic graph.
Official references


Author: Herman Schoenfeld