Reputation: 11592
I have a TreeView in C# Windows Form. If the user selected one node, then I want to retrieve the immediate next node and also immediate previous node of the treeview. Don't consider if it is sibling or any other. I want to just pick up immediate next node and also immediate previous node.
See this picture:
Suppose user Selecting following case ==> I want to retrieve this node
0 1.Sample Data ==>1 When multiple agents...
1 When multiple agents... ===>2 The second major ...
2 The second major ... ===>3 In this case....
3 In this case.... ===>4 2.Target Settings...
and so on..
How can I achieve this?
Upvotes: 2
Views: 3975
Reputation: 51
This code works perfectly in my opinion. NextVisibleNode - solves the problem
if (treeView.SelectedNode != null) {
var currentNode = treeView.SelectedNode;
while(currentNode.NextVisibleNode != null ) {
currentNode = currentNode.NextVisibleNode;
if (currentNode.Checked) { break; }
}
MessageBox.Show("Next checked node is " + currentNode.Text);
}
Upvotes: 0
Reputation: 21
I've stumbled across this question having the same issue, so here's my solution to the issue:
Assuming start is the TreeNode to begin with, going "down"
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;
}
}
}
}
Upvotes: 1
Reputation: 8786
use e.Node.NextNode
and e.Node.PrevNode
for sibling node.
EDIT
or e.Node.NextVisibleNode
and e.Node.PrevVisibleNode
in your case for visible node.
TreeNode.NextVisibleNode Property
TreeNode.PrevVisibleNode Property
please refer to MSDN for other TreeNode
properties: TreeNode Properties
Upvotes: 3
Reputation: 2355
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;
}
For the cases you can do this :
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];
}
}
Upvotes: 2