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" );
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.
source share