How can I get a list of all tree nodes (in all levels) in a TreeView
control?
Assuming you have a tree with one root node the following code will always loop the tree nodes down to the deepest, then go one level back and so on. It will print the text of each node. (Untested from the top of my head)
TreeNode oMainNode = oYourTreeView.Nodes[0];
PrintNodesRecursive(oMainNode);
public void PrintNodesRecursive(TreeNode oParentNode)
{
Console.WriteLine(oParentNode.Text);
// Start recursion on all subnodes.
foreach(TreeNode oSubNode in oParentNode.Nodes)
{
PrintNodesRecursive(oSubNode);
}
}
This code help you to iterate though all TreeView list with identifying current depth level. Code can be used to save TreeView items to XML file and other purposes.
int _level = 0;
TreeNode _currentNode = treeView1.Nodes[0];
do
{
MessageBox.Show(_currentNode.Text + " " + _level);
if (_currentNode.Nodes.Count > 0)
{
_currentNode = _currentNode.Nodes[0];
_level++;
}
else
{
if (_currentNode.NextNode != null)
_currentNode = _currentNode.NextNode;
else
{
_currentNode = _currentNode.Parent.NextNode;
_level--;
}
}
}
while (_level > 0);