【发布时间】:2023-03-14 14:15:01
【问题描述】:
我有一个树视图控件,它包含一个父节点和来自该父节点的几个子节点。有没有办法从主父节点获取所有子节点的数组或列表?即从 treeview.nodes[0] 或第一个父节点获取所有节点。
【问题讨论】:
我有一个树视图控件,它包含一个父节点和来自该父节点的几个子节点。有没有办法从主父节点获取所有子节点的数组或列表?即从 treeview.nodes[0] 或第一个父节点获取所有节点。
【问题讨论】:
public IEnumerable<TreeNode> GetChildren(TreeNode Parent)
{
return Parent.Nodes.Cast<TreeNode>().Concat(
Parent.Nodes.Cast<TreeNode>().SelectMany(GetChildren));
}
【讨论】:
您可以像这样递归地添加到列表中:
public void AddChildren(List<TreeNode> Nodes, TreeNode Node)
{
foreach (TreeNode thisNode in Node.Nodes)
{
Nodes.Add(thisNode);
AddChildren(Nodes, thisNode);
}
}
然后调用这个程序传入根节点:
List<TreeNode> Nodes = new List<TreeNode>();
AddChildren(Nodes, treeView1.Nodes[0]);
【讨论】:
你可以做这样的事情..来获取树视图中的所有节点..
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);
}
}
请你看看这个链接。
【讨论】: