O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

CREATING CONTROLS

Usually you add controls to a form graphically at design time. In some cases, however, you may want to add new controls to a form while the program is running. This gives you a bit more flexibility so that you can change the program’s appearance at run time in response to the program’s needs or the user’s commands.

For example, you may not know how many pieces of data you will need to display until run time. Sometimes you can display unknown amounts of data using a list, grid, or other control that can hold a variable number of items, but other times you might like to display the data in a series of labels or text boxes. In cases such as these, you need to create new controls at run time.

The following code shows how a program might create a new Label control at run time. First it declares a variable of type Label and initializes it with the New keyword. It uses the label’s SetBounds method to position the label on the form and sets its Text property to “Hello World!” The code then adds the label to the current form’s Controls collection. (“Me” is a keyword that means “the object currently executing code,” which in this case is the form.)

Dim lbl As New Label
lbl.SetBounds(10, 50, 100, 25)
lbl.Text = "Hello World!"
Me.Controls.Add(lbl)
CHANGING CONTAINERS
To place a control inside a container other than the form, add the control to the container’s Controls collection. For example, to add the previous Label to a GroupBox named grpLabels, you would use the statement ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required