列表框中显示的Treeview节点 [英] Treeview nodes shown in listbox
本文介绍了列表框中显示的Treeview节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
单击按钮时(MoveBtn)如何将树视图中选定的项目复制到列表框。
When a button is clicked (MoveBtn )How do I copy over the items selected in my tree view to a listbox.
private void MoveBtn_Click(object sender, EventArgs e)
{
Listbox1.Items.Clear();
foreach (var node in treeView1.Nodes)
{
Listbox1.Items.Add(node);
}
Listbox1.Show();
}
此代码仅显示根,但不显示子节点选择。但是我也希望显示子节点 - 如果可能的话只显示子节点
我尝试了什么:
}
This code only shows the root, but not the child nodes which are selected. But I want to show the child nodes too -- if possible only the child nodes
What I have tried:
Listbox1.Items.Clear();
foreach (var node in treeView1.Nodes)
{
Listbox1.Items.Add(node);
}
Listbox1.Show();
推荐答案
为了复制所有节点,您需要递归。考虑下面的例子(抱歉打字错误,我手边没有编译器)
In order to copy all the nodes you need a recursion. Consider the following example (sorry about the typos, I don't have a compiler at hand at the moment)
public void Method1() {
Listbox1.Items.Clear();
AddNodes(treeView1.SelectedNode, Listbox1);
}
public void AddNodes(TreeNode parentNode, ListBox lb) {
foreach (var node in parentNode.Nodes) {
lb.Items.Add(node);
AddNodes(node, lb);
}
}
注意:Web Ms TreeView提供了对所有已检查TreeNode的轻松访问:WinForms TreeView TreeView不能。 br />
因此,您需要一种方法来获取所有TreeNodes,然后您需要选择所有TreeNodes被检查。此示例使用Eric Lippert提倡的经典基于堆栈的方法,以避免可能的递归堆栈溢出:
Note: the Web Ms TreeView offers easy access to all checked TreeNodes: the WinForms TreeView TreeView does not.
So, you need a method to get all the TreeNodes, and then you need to select all the TreeNodes that are checked. This example uses the "classic" stack-based method that Eric Lippert advocates in order to avoid possible stack overflow with recursion:
public IEnumerable<TreeNode> GetNodes(TreeNodeCollection nodes)
{
var stack = new Stack<TreeNode>();
foreach (TreeNode node in nodes)
{
stack.Push(node);
}
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current;
foreach (TreeNode child in current.Nodes)
{
stack.Push(child);
}
}
}
然后过滤它们以找到选中的节点:
Then filter them to find the checked Nodes:
listBox1.Items.Clear();
var checkedNodes = GetNodes(treeView1.Nodes)
.Where(nd => nd.Checked)
.OrderBy(nd => nd.Text) // remove if you don't want sorted
.ToArray();
listBox1.Items.AddRange(checkedNodes.ToArray());
这篇关于列表框中显示的Treeview节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文