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)
Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.