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

TreeView is a great way to present a hierarchy to users, but imagine the following scenario with the hierarchy shown 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 insert into the database when the user clicks on the Payment node. Essentially, the variables needed for insertion are Building_Id, Tenant_Id, Payment_Id. One way to assemble them is to go to the parent of each node:

 Building_Id = Payment.ParentNode.ParentNode.Id 

Is it better to store all id values โ€‹โ€‹in Payment Node in the following format, then analyze the values โ€‹โ€‹for Building_Id, Tenant_Id, Payment_Id? For instance:

 Payment.Value = "1|2|1" 
+4
source share
3 answers

I believe the best way to handle extra data is to subclass TreeNode. I create a BaseNode class that contains the common data that I want to support, and inherit further from them for any specific node types.

The value of the subclass is that you can support strong data types and complex data types, like any other class ... that avoids breaking into arrays into a string with channel delimiters, etc.

Once you have your nodes, you can offer the same tree that you offer, except that now you extract values โ€‹โ€‹from (say) BaseNode.MyData (which all your subtypes inherit from).

One thing to watch out for if you do this: you need to understand how authoritative you want these nodes to be. In my case, when the user moves through the tree, we check it with the database cache to make sure that we do not need to re-populate the data.

+4
source

If the TreeNodes of the TreeView control has a Tag property that contains the object, you can associate a custom object containing these desired properties with each TreeNode tag, after which you can access them as needed.

For example, in .Net from 4.5 it will be like this:

 myTreeNode.Tag = myObject; 

Where myTreeNode is an instance of TreeNode , and myObject is an instance of your custom object that contains the data that you want to associate with the TreeNode your TreeView .

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

+5
source

You might think that Godeckโ€™s idea would continue, and instead of subclassing TreeNode, attach nodes to a collection of business objects โ€” by storing local data in the properties of the children of the collection. The logic of data collection can provide you with the data you need, and you get the benefits of sharing data and logic at the presentation level.

+1
source

All Articles