views:

378

answers:

2

The TreeView is a nice way to present a hierarchy to users, but imagine the following scenario with the hierarchy depicted below:

Building 1 
 -Tenant 1
   - Payment 1
   - Payment 2
Building 2
 -Tenant 1
   - Payment 1
 -Tenant 2
   - Payment 1
   - Payment 2

where you need to do an insert to a database when the user clicks on the Payment node. Essentially the variables required for the insert are Building_Id, Tenant_Id, Payment_Id. One way to assemble these is to walk to the parent of each node:

Building_Id = Payment.ParentNode.ParentNode.Id

Is it better to store all of the values of the id's on the Payment Node in the following format, then parse the values for Building_Id, Tenant_Id, Payment_Id? For example:

Payment.Value = "1|2|1"
+2  A: 

I find the best way to handle additional data is to subclass TreeNode. I create a BaseNode class that contains the shared data I want to maintain, and inherit further from that for any specific node types.

The value of subclassing is that you can maintain strong data types and complex data types just like any other class... which avoids hacking arrays into a string with pipe separators and the like.

Once you have your nodes in place it allows the same tree walk you propose, except now you are pulling the values from (say) BaseNode.MyData (which all your subtypes will inherit).

One thing to watch for if you do this though: you need to understand how authoritative you want these nodes to be. In my case, when the user navigates the tree we check with a database cache to ensure we don't need to repopulate the data.

Godeke
Great answer - just what I was looking for. Thanks!
David Robbins
+1  A: 

You might consider taking Godeke's idea further and instead of subclassing the TreeNode, tie the nodes to a business object collection - storing your local data in properties of the collection children. The collection logic will be able to give you the data you need and you gain the benefits of separating the data and logic from the presentation layer.

Doug L.