TreeView::BeforeCollapse Event


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Occurs before the tree node is collapsed.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

event TreeViewCancelEventHandler^ BeforeCollapse {
	void add(TreeViewCancelEventHandler^ value);
	void remove(TreeViewCancelEventHandler^ value);

For more information about how to handle events, see Handling and Raising Events.

The following code example demonstrates how to change the collapse state of a TreeView so that all the checked nodes are visible. First, all the nodes are expanded, and a handler is added for the BeforeCollapse event. Next, all the nodes are collapsed. The BeforeCollapse event handler determines whether a given node has child nodes that are checked. If a node has checked children, the collapse is canceled for that node. In order to allow standard node collapse when the minus sign next to a node is clicked, the BeforeCollapse event handler is then removed.

This behavior can also be implemented by handling the BeforeExpand event, as illustrated in the example for that topic.

For the complete example, see the TreeView constructor reference topic.

   void showCheckedNodesButton_Click( Object^ /*sender*/, EventArgs^ /*e*/ )

      // Disable redrawing of treeView1 to prevent flickering 
      // while changes are made.

      // Collapse all nodes of treeView1.

      // Add the checkForCheckedChildren event handler to the BeforeExpand event.
      treeView1->BeforeCollapse += checkForCheckedChildren;

      // Expand all nodes of treeView1. Nodes without checked children are 
      // prevented from expanding by the checkForCheckedChildren event handler.

      // Remove the checkForCheckedChildren event handler from the BeforeExpand 
      // event so manual node expansion will work correctly.
      treeView1->BeforeCollapse -= checkForCheckedChildren;

      // Enable redrawing of treeView1.

   // Prevent collapse of a node that has checked child nodes.
   void CheckForCheckedChildrenHandler( Object^ /*sender*/, TreeViewCancelEventArgs^ e )
      if ( HasCheckedChildNodes( e->Node ) )
            e->Cancel = true;

   // Returns a value indicating whether the specified 
   // TreeNode has checked child nodes.
   bool HasCheckedChildNodes( TreeNode^ node )
      if ( node->Nodes->Count == 0 )
            return false;

      System::Collections::IEnumerator^ myEnum = node->Nodes->GetEnumerator();
      while ( myEnum->MoveNext() )
         TreeNode^ childNode = safe_cast<TreeNode^>(myEnum->Current);
         if ( childNode->Checked )
                  return true;

         // Recursively check the children of the current child node.
         if ( HasCheckedChildNodes( childNode ) )
                  return true;

      return false;

.NET Framework
Available since 1.1
Return to top