AfterExpand / AfterCollapse event handling
Add AfterExpand and AfterCollapse event handlers for the tree to handle the reaction to expand / collapse nodes. I hard-coded the add-on for this example, but essentially itβs just the height of the menus, buttons, etc. That will be used to resize the form.
Private Sub Rapports_tvAllReports_AfterExpand(sender As Object, e As System.Windows.Forms.TreeViewEventArgs) Handles Rapports_tvAllReports.AfterExpand, Rapports_tvAllReports.AfterCollapse Dim Padding As Integer = 140 'Customize this, basically accounts for all buttons or menus included in the form which nests the treeview Dim TreeViewHeight As Integer = GetOpenedNodesRecursively(Rapports_tvAllReports) If formWindow = FormWindowState.Normal Then Me.Size = New Size(345, TreeViewHeight + Padding) End Sub
All we do is increase Y and set a new Y in the form. To make treeview resize correctly with the shape, snap to the top and bottom .
Recursively pass through nodes
This function will go through the root nodes and call a recursive function on open nodes.
Private Function GetOpenedNodesRecursively(ByVal aTreeView As TreeView) Dim Y As Integer = 0 'Go through each node of the treeview (first level) For Each n As TreeNode In aTreeView.Nodes Y += Rapports_tvAllReports.ItemHeight 'If the user expands a node, recursively increment the Y If n.IsExpanded Then Y += RecursiveYIncrement(n) Next Return Y End Function
Now just continue to grow the TreeViewHeight with a recursive function that will return the height (Y) of all nodes that are expanding in the current tree view.
Private Function RecursiveYIncrement(ByVal n As TreeNode) Dim Y As Integer = 0 'Go through each node of the treeview (first level) For Each aNode As TreeNode In n.Nodes Y += Rapports_tvAllReports.ItemHeight 'If the user expands a node, recursively increment the Y If aNode.IsExpanded Then Y += RecursiveYIncrement(aNode) Next Return Y End Function
Visual reproduction
Here's what it looks like when we are done:
Let's start with a minimized tree view

Then we can expand some nodes and the shape will grow accordingly 
And then we can again collapse the nodes and expand them, the form is again configured! 
Forgive me for the French in the screenshots, this is the norm here in Quebec ... We must do this!