Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I process the newly selected node in a TreeView when handling the Click event?

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



Page view counter