There may be times when you need to move and appropriately resize the controls on a form. In this quick tip, I show how to set the controls in VB.NET forms so you can properly resize the controls based on the size of the form.
Using the Anchor property
A simple way to make sure the form's controls are moved and/or resized in accordance to the container form is to use the control's Anchor property. In general, this property allows the control to maintain a constant relationship with the side(s) of the form specified in the Anchor property. For instance, setting an Anchor property of a TextBox control on a form to Left allows the control to always be the same distance from the Left edge of the form when it's resized. You can Anchor a control to the Right, Left, Top, Bottom, or any combination of the above. If you set the Anchor property to all four sides, it allows a control to be resized with the form.
For example, add a TextBox control to your form, set its Multiline property to True, and its Anchor property to all four sides. See Figure 1. The result of debugging the form will look like Figure 2. Now resize the form to make it bigger, and the text control will be resized together with the form as in Figure 3.
Note: In this example, setting the TextBox control's Multiline property to True allows its height to be adjusted when the form's height changes. If the TextBox control's Multiline property is set to False, only the control's width will get adjusted when the form's size is changed—even when the TextBox is anchored to all four sides of the form.
Miss a tip?
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!