When I get the SelectedNode in the TreeView's Click event, it is the previous selection. How do I get the newly selected node?
Use the AfterSelect event instead of the Click event. The Click event is inherited from Control.Click and occurs before the new selection is set into SelectedNode. The AfterSelect event is fired after the newly selected node is placed in the SelectedNode property. This code illustrates these events.
private void treeView1_AfterSelect( object sender, TreeViewEventArgs e )
{
TreeNode node = treeView1.SelectedNode;
Console.WriteLine("AfterSelect:" + node.ToString()); // from tree
Console.WriteLine("AfterSelect:" + e.Node.ToString()); // from event args
}
private void treeView1_Click( object sender, EventArgs e )
{
TreeNode node = treeView2.SelectedNode;
if ( node == null )
Console.WriteLine( "Click: (none)" );
else
Console.WriteLine( "Click: " + node.ToString() );
}
Contributed from George Shepherd's Windows Forms FAQ