Search code examples
c#winformsresizetreeviewsplitcontainer

Prevent Windows form elements from leaving view when resizing from the bottom?


I have a form set up as shown in the picture below. The form simply contains a SplitContainer with two TreeViews in each of the panels, plus the label above the TreeView.

Here's a picture of the form that has not yet been resized:

Each TreeView is anchored to the Top and Left, and docked to the Bottom. Each label is anchored to the Top and Left. The SplitContainer is anchored to the Bottom, Left, and Right.

The above settings allow me to resize the TreeViews equally when the form is resized. However, when I resize the form's height, the labels (and of course the TreeViews as well) are pushed out of the form view, as shown in this picture:

How can I prevent the elements from being pushed past the title bar? Preferrably without the use of a SizeChanged event. I have tried adding padding to the form, as well as trying different docking/anchor modes, but I have been unable to restrict this.


Solution

  • Perform the following steps in order:

    1. Either anchor the SplitContainer to all 4 sides or dock-fill it.
    2. Place the labels on the panels. Make them smaller than the panels, in order to be sure that they really become child controls of the panels (and not of the form). Set their Dock property to Top.
    3. Place the TreeViews on the panel. It is important that this is done after you placed and docked the labels! Same thing here: make them smaller than the panels. Then set their Dock property to Fill.

    Note: you can either dock or anchor a control, but not both! The Anchor property is ignored if Dock is something else than None. An anchored edge keeps a constant distance to the side it is anchored to. If an edge is not anchored, the size of the control in this direction will remain unchanged. If two corresponding edges (e.g. left and right) are not anchored, then the control will be centered in this direction.

    See: Manage WinForm controls using the Anchor and Dock properties