[英]C# treeView, how do I get the parent nodes when user clicks the child node
I have a treeview which is generated programatically when documents are loaded into my programme. 我有一个树形视图,当文档加载到程序中时会以编程方式生成。
My treeview looks something like this: 我的树视图看起来像这样:
+ System - 65
+ Subsystem - 32
Subsystem - 68
+ Subsubsystem - 01
Subsubsystem - 02
+ System - 70
+ Subsystem - 22
Subsystem - 30
+ Subsubsystem - 10
I need to be able to click on a 'Subsubsystem' child node and have it poplulate my listView with all documents that belong to the respective System and subsystem. 我需要能够单击“ Subsubsystem”子节点,并将其填充到属于各自System和子系统的所有文档的listView中。 So for example, if i were to click on the Subsubsystem 10 of the treeview above, i need it to return all documents which are part of System 70, Subsystem 30 and Subsubsystem 10.
因此,例如,如果我要单击上面树视图的子系统10,则需要它返回系统70,子系统30和子系统10的所有文档。
The bit i'm struggling with is knowing how to get the parent nodes of the Subsubsystem 10 when i click on it. 我苦苦挣扎的一点是,当我单击它时,我知道如何获取子系统10的父节点。
Obviously when i click on the Subsubsystem 10 my programme needs to get the parent nodes in order to return the documents belonging to the respective system and subsystem. 显然,当我单击子系统10时,我的程序需要获取父节点,以便返回属于各自系统和子系统的文档。
Any ideas? 有任何想法吗?
Use the afterselect event of your treeview. 使用树视图的afterselect事件。 In the TreeViewEventArgs, there is your current node.
在TreeViewEventArgs中,有您当前的节点。 That node has a property parent.
该节点具有父属性。
private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
e.Node.Parent
}
you can use TreeNode.Parent Property
on AfterSelect
event 您可以在
AfterSelect
事件上使用TreeNode.Parent Property
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if(e.Node.Parent!= null &&
e.Node.Parent.GetType() == typeof(TreeNode) )
{
// do something with e.Node.Parent
}
else
{
//"No parent node.";
}
}
Or you can get the parent from treeView1.SelectedNode.Parent
或者您可以从
treeView1.SelectedNode.Parent
获取父级
I use a simple loop to do this 我使用一个简单的循环来做到这一点
private TreeNode[] GetParentNodes(TreeNode node_)
{
TreeNode[] nodes_ = new TreeNode[node_.Level +1];
nodes_[0] = node_;
for (int i = 1; i < nodes_.Length; i++)
{
nodes_[i] = nodes_[i -1].Parent;
}
return nodes_;
}
and call it from the click event (right click in my case) of the tree 并从树的点击事件(在我的情况下为右键)调用它
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
processClick(e);
}
}
private void processClick(System.Windows.Forms.MouseEventArgs e)
{
System.Drawing.Point p = new System.Drawing.Point(e.X, e.Y);
TreeNode node = treeView1.GetNodeAt(p);
treeView1.SelectedNode = node;
}
It can be cleaned up significantly, but the general idea works. 可以对其进行重大清理,但总体思路可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.