How can I bind an object to a TreeView (WinForms) node in C#?
I thought of something like ExNode : Windows.Forms.Node that can take an object as member besides the treenode name... however I am not sure that is the right approach.
To bind local data to the TreeView, you can assign a JavaScript object array to the dataSource property. The TreeView component requires three fields (ID, text, and parentID) to render local data source.
You can bind a TreeView control to an XML file by creating an XmlDataSource control that represents the XML file and then assigning that XmlDataSource to your TreeView control.
A typical tree structure has only one root node; however, you can add multiple root nodes to the TreeView control. The Nodes property can also be used to manage the root nodes in the tree programmatically. You can add, insert, remove, and retrieve TreeNode objects from the collection.
imho you have several strategies :
stick an object of any type in the Tag property of any Node : downside : you'll have to cast it back to its 'native form' when you retrieve it to use it : if that "native form" is anything but type 'Object.
sub-class TreeNode, and add a public fields, Public Properties, or whatever, for your objects ... or even List ... ... or whatever you need to associate with the Node.
assuming your objects are of the same type, you could create a dictionary of type : Dictionary <TreeNode, myObjectType>, instantiate it, and, as needed, store a TreeNode and its associated Object(s) that way as a Key/Value Pair.
Strategies #1, and #3 have the advantage that you can store an associated object ONLY as needed Strategy #2 : is more suited to the case where you anticipate every TreeNode is going to have an associated object(s).
Of course with stragies #1 and #3, you will need to test at run-time for the presence or absence of an object associated with a particular Node.
Strategy #1's an easy test : if the Tag propety of the Node is Null : you know there's no object : if not null ... and there may be more than one type of object stored in the Tag field ... then you'll have to pull out the Tag object, and make sure it's the right type as in : (the example that follows assumes a public class, "Class1," has been assigned to tag of the first node in the TreeView :
TreeNode thisNode = theTreeView.Nodes[0];
if (((thisNode.Tag != null) && (thisNode.Tag is Class1))) ... handle the object ...
Strategy #3 is a little easier since you can just evaluate if the Dictionary<Node, myObject>.Contains the Node as a Key.
Are you looking for something like the Tag property on TreeNodes? It can hold any object.
http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With