C# TreeView Traversing






2.75/5 (23 votes)
Mar 20, 2006

75471

1652
This article presents a simple c# TreeView traversal mechanism.
Introduction
TreeView in C# is a great control. TreeView can be used to build Hierarchical Menus. I was involved in a project where i had to make use of TreeView quite heavily and as a result i wrote some code myself to Build the TreeView dynamically (database driven). Here i present the TreeView traversal operation.
Here's a snapshot of the Populated TreeView.
Here is the code:
class TVIEW
//1- Create a TreeView
TreeView treeview =
new TreeView();
//2- Populate the TreeView with Data
//populateTreeView();
//3- Now You can visit each and every node of this treeview whenever you require
TVIEW t1 =
new TVIEW();t1.TraverseTreeView(treeview);
private void TraverseTreeView(TreeView tview)
{
//Create a TreeNode to hold the Parent Node
TreeNode temp = new TreeNode();
//Loop through the Parent Nodes
for(int k=0; k<tview.Nodes.Count; k++)
{
//Store the Parent Node in temp
temp = tview.Nodes[k];
//Display the Text of the Parent Node i.e. temp
MessageBox.Show(temp.Text);
//Now Loop through each of the child nodes in this parent node i.e.temp
for (int i = 0; i < temp.Nodes.Count; i++)
visitChildNodes(temp.Nodes[i]); //send every child to the function for further traversal
}
private void visitChildNodes(TreeNode node)
{
//Display the Text of the nodeMessageBox.Show(node.Text);
//Loop Through this node and its childs recursivelyfor (int j = 0; j < node.Nodes.Count; j++)visitChildNodes(node.Nodes[j]);
}