Can you bind data to a TreeView control?

Typically, when I use the standard TreeView control that comes with C # / VB, I write my own methods to transfer data to and from the internal repository of the tree hierarchy.

There may be ways to "bind" the GUI to a data store that I can point to (for example, XML files), and when the user edits the elements of the tree, he must save it back to the store. Is there any way to do this?

+5
source share
2 answers

The following article should allow you to do what you want.
http://www.codeproject.com/KB/tree/bindablehierarchicaltree.aspx

Edit: If you don't need something as complex as the above, the following might be simpler / more appropriate: http://www.codeproject.com/KB/tree/dbTree.aspx

Edit 2: If you want this to respond to changes in the tree, you probably need the first option.

+6
source

I dealt with this by creating a class that inherits from TreeNode and contains an object. then you can bind the record to the node and call it during the Click or DoubleClick event. For example.

class TreeViewRecord:TreeNode
    {
        private object DataBoundObject { get; set; }

        public TreeViewRecord(string value,object dataBoundObject)
        {
            if (dataBoundObject != null) DataBoundObject = dataBoundObject;
            Text = value;
            Name = value;
            DataBoundObject = dataBoundObject;
        }

        public TreeViewRecord()
        {
        }

        public object GetDataboundObject()
        {
            return DataBoundObject;
        }
    }

then you can bind to each node how you build a TreeView, for example.

TreeView.Nodes.Add(new TreeViewRecord("Node Text", BoundObject));
//or for subNode
TreeView.Nodes[x].Nodes.Add(new TreeViewRecord("Node Text", BoundObject));

DoubleClick -

private void TreeViewDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
             object exp = ((TreeViewRecord) e.Node).GetDataboundObject();
             //Do work
        }
0

All Articles