Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store data on a TreeView Node?

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"
like image 552
David Robbins Avatar asked Dec 23 '22 12:12

David Robbins


2 Answers

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.

like image 135
Godeke Avatar answered Jan 28 '23 05:01

Godeke


If the TreeNodes of the TreeView control have a Tag property that holds an object, you can associate a custom object containing those desired properties with each TreeNode's tag, then you can access them as necessary.

For example, in .Net as of 4.5, it would be like this:

myTreeNode.Tag = myObject;

Where myTreeNode is an instance of TreeNode and myObject is an instance of the custom object you defined which contains the data you wish to have associated with a TreeNode of your TreeView.

Here is an article on MSDN on the TreeNode.Tag property: MSDN - TreeNode.Tag Property.

like image 26
Derek W Avatar answered Jan 28 '23 04:01

Derek W