Directory Structure using Tree View
This code snippet will give you a solution to display directory structure of given path. And it will explain how to bind data to tree view dynamically. Here is your aspx code
< asp:Panel ID="pnl" runat="server" > < /asp:Panel >
to this panel i am going to add a tree view dynamically using C# code which will looks like the following.
protected void Page_Load(object sender, EventArgs e)
//initializing a new Tree view control
TreeView TV = new TreeView();
//Getting the Main directory for which we need to show the tree view. Here i am using complete "E drive".
DirectoryInfo dir = new DirectoryInfo("E:\\");
//Getting all the main directories from above given path.
foreach (DirectoryInfo subdir in dir.GetDirectories())
//creating a new node for every directory.
TreeNode TN = new TreeNode();
//Calling a recursive function which will give complete structure of this node.
TN = GetSubItems(subdir);
//Adding node to tree view.
}//end of for loop.
//adding the Tree View control to our Panel.
Our Recursive function will look like this.
/// Method to get the complete depth of the given tree node in a tree structure.
///Paramter : Directory for which we want the complete depth.
///Returns a Tree node with full depth of the directories of the given directory.
private TreeNode GetSubItems(DirectoryInfo Dir)
//initializing new tree node.
TreeNode TN = null;
TN = new TreeNode();
//assignning the name and value of the directory.
TN.Text = Dir.Name;
TN.Value = Dir.FullName;
//Loop to check the given directory contains sub directories or not,
//if any sub directory is found this function will be called recursively.
foreach (DirectoryInfo subdir in Dir.GetDirectories())
//Initializing child tree node for the sub diretory.
TreeNode ChildNode = new TreeNode();
//Checking for sub directories.
//calling method recursively for sub directories.
ChildNode = GetSubItems(subdir);
//if the given directory doesn't have any sub directories we will just add name and value for that.
ChildNode.Text = subdir.Name;
ChildNode.Value = subdir.FullName;
//adding child node to main node
}//end of for loop
//returning the node.
If your directory contains more number of directories it will take some time to display. Hope this will helpful.
Rate me if you like this code snippet.