TreeView: SelectedNode not working for me

Im using the following code:

TreeNode i = treeView1.SelectedNode; RefillTree(); //clears the tree and rebuilt it again. treeView1.SelectedNode=i; 

However, the SelectedNode is still null, however the "i" is correctly referenced.

I will need to select and deploy a specific node automatically after updating the tree.

thanks

+4
source share
3 answers

What does "RefillTree" exactly do? If it removes the Node referenced by "i", then I expect that setting the SelectedNode property to Node, which does not exist in the control, will have no effect.

EDIT:

I can almost guarantee that you are cleaning the control and creating new nodes to populate it. It does not matter if these new nodes contain the same data, SelectedNode looks for the uniformity of the object and does not find a match. for example, this code reproduces your problem:

 treeView1.nodes.Add( new TreeNode( "Node 1" ) ); treeView1.nodes.Add( new TreeNode( "Node 2" ) ); treeView1.SelectedNode = new TreeNode( "Node 1" ); // null reference exception here, we did not find a match MessageBox.Show( treeView1.SelectedNode.ToString( ) ); 

So, you can find the Node by value after clearing the control:

 TreeNode node1 = new TreeNode( "Node 1" ); TreeNode node2 = new TreeNode( "Node 2" ); treeView1.Nodes.Add( node1 ); treeView1.Nodes.Add( node2 ); treeView1.Nodes.Clear( ); treeView1.Nodes.Add( "Node 1" ); treeView1.Nodes.Add( "Node 2" ); // you can obviously use any value that you like to determine equality here var matches = from TreeNode x in treeView1.Nodes where x.Text == node2.Text select x; treeView1.SelectedNode = matches.First<TreeNode>( ); // now correctly selects Node2 MessageBox.Show( treeView1.SelectedNode.ToString( ) ); 

Using LINQ here seems awkward, but the TreeNodeCollection class provides only the Find () method, which uses the Node Name property. You can also use this, but equally awkwardly.

+3
source

Detecting a node by name will work, however, be careful if you have multiple nodes with the same name in different branches.

A good solution I'm using is to save the selected node path:

 selected_node_path = tree.SelectedNode.FullPath 

Then, when you rebuild the treeview structure, set the added node as selected, after it has been added to the tree:

  ' create your node newnode = New TreeNode("node name") ' add it to the tree, it then gets a path tree.Nodes.Add(newnode) ' test if it the same path If (newnode.FullPath = selected_node_path) Then tree.SelectedNode = newnode 

PS is not against VB, but you get the general idea

+3
source

RefillTree replaces node, so I no longer exist when you try to reset the selected node.

EDIT: try this code

  Dim RememberMe As String = TreeView1.SelectedNode.Name() RefillTree() Dim FoundNode() As TreeNode = TreeView1.Nodes.Find(RememberMe, True) If FoundNode.Length > 1 Then ' oops, we didn't give unique values! Else TreeView1.SelectedNode = FoundNode(0) End If 
0
source

All Articles