Tuesday, August 14, 2007

ASP.NET Tree view of object structure

Okay. Let's say you have an object tree in ASP.NET and you want to display it to the user.

For our purposes, let's say we have a DataNode class with the following fields: name, description, an array of children, and a link back to its parent. To be able to do this nicely, we need to implement two interfaces, IHierarchicalEnumerable (henceforth IHE)(this one is clear from the docs), and IHierarchyData (henceforth IHD)(this is seen in the docs but is not clear).

Now for the IHE interface, we need to implement a GetHierarchyData function. This returns an object that lets one navigate the hierarchy of another object in the hierarchy. We'll choose that object itself, so we have:

public IHierarchyData GetHierarchyData(object enumeratedItem)
{
return (IHierarchyData)enumeratedItem;
}


In addition, IHierarchicalEnumerable is a sub-interface of IEnumerable, so we need to have a GetEnumerator function. Just use the enumerator of whatever data structure holds the list of children:

public IEnumerator GetEnumerator()
{
return children.GetEnumerator();
}


That's the easy part. Now for the IHierarchyData:
GetChildren needs to return an IHierarchicalEnumerable. We can just return "this", since we know how to enumerate our own children.

GetParent returns the parent object of our current object; HasChildren should be obvious.

Path does not look like it is actually used, and neither do Item and Type, so just return something there for completeness. Now to get the tree view to display what you want, set its TextField to whatever property of your object you want (such as Name). Note that this must be a .NET property, a public field is not kosher.

Soon I'll work on allowing editing of this hierarchy.

0 comments: