List all child nodes of a parent node in a treeview control in Visual C#
I have a treeview control, and it contains a single parent node and several child nodes from that parent. Is there a way to obtain an array or list of all the child nodes from the main pa开发者_如何学Pythonrent? i.e. getting all the nodes from treeview.nodes[0], or the first parent node.
public IEnumerable<TreeNode> GetChildren(TreeNode Parent)
{
return Parent.Nodes.Cast<TreeNode>().Concat(
Parent.Nodes.Cast<TreeNode>().SelectMany(GetChildren));
}
You can add to a list recursively like this:
public void AddChildren(List<TreeNode> Nodes, TreeNode Node)
{
foreach (TreeNode thisNode in Node.Nodes)
{
Nodes.Add(thisNode);
AddChildren(Nodes, thisNode);
}
}
Then call this routine passing in the root node:
List<TreeNode> Nodes = new List<TreeNode>();
AddChildren(Nodes, treeView1.Nodes[0]);
You could do something like this .. to get the all nodes in tree view ..
private void PrintRecursive(TreeNode treeNode)
{
// Print the node.
System.Diagnostics.Debug.WriteLine(treeNode.Text);
MessageBox.Show(treeNode.Text);
// Print each node recursively.
foreach (TreeNode tn in treeNode.Nodes)
{
PrintRecursive(tn);
}
}
// Call the procedure using the TreeView.
private void CallRecursive(TreeView treeView)
{
// Print each node recursively.
TreeNodeCollection nodes = treeView.Nodes;
foreach (TreeNode n in nodes)
{
PrintRecursive(n);
}
}
would you pls take alook at this link .
http://msdn.microsoft.com/en-us/library/wwc698z7.aspx
精彩评论