Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

24. Windows Forms TreeView

24.5 When I get the SelectedNode in the treeview's Click event, it is the old selection. How do I get the newly selected node?


Try using 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 treeView2_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
     TreeNode node = treeView2.SelectedNode;
     Console.WriteLine("AfterSelect:" + node.ToString());//from tree
     Console.WriteLine("AfterSelect:" + e.Node.ToString());//from event args

}

private void treeView2_Click(object sender, System.EventArgs e)
{
     TreeNode node = treeView2.SelectedNode;
     if(node == null)
          Console.WriteLine("Click: (none)");
     else
          Console.WriteLine("Click: " + node.ToString());
}