Download demo application - 6.57 KB
In this blog I'm going to explain how you can bind a TreeView control to a hierarchical data through recursion.
Simply drag and Drop a TreeView control by keeping the value of AutoGenerateDataBindings property equal to false.
Target Hierarchical Data
Target hierarchical data that I've chosen for this demo is a folder's hierarchical structure.
Binding TreeView Control
The TreeView control for this demo has been bind in the Page_Load event through the BindTreeView method as-
In this method a TreeView node for the top root folder of given folder hierarchical structure has been created with the help of GetNode method and then recursive BindChildNode method is invoked.
This method is simply used to create a TreeView node. Each TreeView node created by this method takes folder name as a Text, folder fully qualified path as a Value and a folder image. It takes DirectoryInfo as an argument.
This method accepts TreeNode as an argument. This method has been invoked recursively to create a hierarchical structure in TreeView control. It starts from a node to create a chain of nodes untill a leave node found for a particular node.
So this is the recursive approach to create a TreeView for a given hierarchichal data. But recursive approach is not good for a very long complex hierarchichal data. For example if you consider C-drive (C:\\) as a hierarchical data source, then it will take very long time to create a TreeView. For this type of data source, On Demand approach is preferred. I'll explain this technique in the next blog.