如何解决如何从C#中Treeview的选定节点获取下一个直接节点?
| 我在C#Windows窗体中有一个TreeView。如果用户选择了一个节点,那么我想检索树视图的直接下一个节点以及直接上一个节点。不要考虑它是否是兄弟姐妹或任何其他。我只想选择直接的下一个节点,也可以选择直接的上一个节点。 看到这张图片: 假设用户选择以下情况==>我要检索此节点 0 1.样本数据==> 1当多个代理... 1当有多个代理时... ===> 2第二专业... 2第二专业... ===> 3在这种情况下... 3在这种情况下...... ===> 4 2.Target Settings ... 等等.. 我该如何实现?解决方法
使用
e.Node.NextNode
和e.Node.PrevNode
作为同级节点。
TreeNode.NextNode属性
TreeNode.PrevNode属性
编辑
或e.Node.NextVisibleNode
和e.Node.PrevVisibleNode
(对于可见节点)。
TreeNode.NextVisibleNode属性
TreeNode.PrevVisibleNode属性
有关其他TreeNode
属性,请参考MSDN:TreeNode属性
, TreeView tr = new TreeView();
private void Form1_Load(object sender,EventArgs e)
{
tr.AfterSelect += new TreeViewEventHandler(tr_AfterSelect);
}
void tr_AfterSelect(object sender,TreeViewEventArgs e)
{
TreeNode PrevNode = e.Node.PrevNode;
TreeNode NextNode = e.Node.NextNode;
}
对于这种情况,您可以执行以下操作:
void tr_AfterSelect(object sender,TreeViewEventArgs e)
{
TreeNode NextNode;
if (e.Node.Nodes.Count == 0)
{
NextNode = e.Node.NextNode;
}
else
{
NextNode = e.Node.Nodes[0];
}
}
, 我偶然遇到了同样的问题,所以这是我对这个问题的解决方案:
假设开始是从TreeNode开始,则“向下”
if (start?.Nodes.Count > 0)
start = start?.Nodes[0]; //If there are childs,select the first
else if (start?.NextNode != null)
start = start?.NextNode; //If there is a sibling,select the sibling
else
{
//In this case,the next node is a sibling of one of the nodes ancestors
if (start?.Parent?.NextNode != null)
start = start?.Parent?.NextNode; //the parents sibling is our next node
else
{
//we go the paths along the parents up,until we can go to the next sibling,//as long as there exist some parents
while(start.Level != 0)
{
start = start.Parent;
if (start.NextNode != null)
{
start = start.NextNode;
break;
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。