I have a table which defines a hierarchy which is self-referencing.
I retrieve the data into a DataSet DataTable, and create a DataRelation for the self-referencing column (i.e. MyID and MyParentID). When I data bind the table to the tree, I see every node in the tree at the first level. Only the TOP node should be at the first level, followed recursively by the children at each level.
What am I missing?
The TOP node in my hierarchy is indicated by a NULL parent ID.
Hi,
You're not missing anything. If you set up a DataSet with a single table and a single relationship which relates the table back to itself, the root-level table is still going to have all of the rows of data. So the tree is just displaying what the DataSet gives it.
You have a couple of options here.
The easiest thing to do would probably be to handle the InitializeDataNode event of the tree. You could check the key value and the ParentNode of each node initialize. If the ParentNode is null, you know the node is at the root level. And then if the ParentID is not null, you know the node should not be visible and you can set the Hidden property on the node to true.
Another option would be to do this on the DataSet. This is a little more complicated coding-wise, but it's probably a bit more efficient. What you would do is create two tables. The first table would be created from a query that only returns rows where the ParentID is null. Then you create a relation from that table to the main table (which includes everything). And then a second relation from teh main table back to itself. This way the data would accurately reflect the structure you want.
The only tricky part about this is that the tree will not have 2 different ColmunSets by default. So you would probably want to turn off AutoGenerateColumnSets and generate one ColumnSet yourself and use it as the RootColumnSet in the tree.
You stated, "the tree will not have 2 different ColumnSets by default". I'm noticing that a ColumnSet is generated for each level in the tree. So, I guess you meant, I should turn off AutoGenerateColumnSets, and generate one ColumSet myself.
Are there any issues with leaving the AutoGenerateColumnSets property on? I'll only have a handful of levels in the tree.
Oops. I guess I mis-spoke there. You are right, the tree will create a ColumnSet for each band because each band will have a different key. Sorry for the confusion.
Having multiple ColumnSets is not necessarily bad - it depends on what you want the sorting behavior to be. If you are using OutlookExpress style in the tree, which is a common case for recursive data), then you probably want your whole tree to use a single ColumnSet so that sorting a column sorts the entire tree.
If you use multiple ColumnSets, then sorting one level will not have any effect on the other levels. Each ColumnSet will sort independently. You may, of course, want that behavior.