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 at run time. 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, suppose that an application might need between 1 and 100 text boxes. Most of the time it needs only a few, but depending on the user’s input, it might need a lot. You could give the form 100 text boxes and then hide the ones it didn’t need, but that would be a waste of memory most of the time. By creating only the number of text boxes actually needed, you can conserve memory in the most common cases.

The following sections explain how to create controls both at design time and at runtime.

Creating Controls at Design Time

To create a control at design time, double-click on a form in Solution Explorer to open it in the form editor. Decide which control you want to use from the Toolbox. If the Toolbox tab you are using is in List View mode, it displays the controls’ names. If the tab displays only control icons, you can hover the mouse over a tool to see a tooltip that gives the control’s name and a brief description.

Figure 2-3 shows a tooltip describing the HelpProvider component. In this example, the tooltip says the control is a HelpProvider, version 2.0.0.0 from Microsoft Corporation, and that it is a .NET component. The last part of the tooltip describes the component’s purpose: “Provides pop-up or online Help for controls.”

image from book
Figure 2-3: Hover the mouse over a toolbox icon to see the tool’s description.

After you have chosen a control, there are several ways you can add it to the form. First, you can double-click on the tool to place an instance of the control on the form at a default size in a default location. After adding the control to the form, the IDE deselects the tool and selects the pointer tool (the upper leftmost tool in the Toolbox’s current tab).

A second way you can add a control to a form is to select it in the Toolbox, and then click and drag to place it on the form. When you click the form without dragging, the IDE adds a new control at that position with a default size. After you add the control, the IDE deselects the tool and selects the pointer tool.

Third, when you click and drag a tool from the Toolbox onto the form, Visual Basic makes a new control with a default size at the position where you dropped the tool.

Fourth, if you plan to add many copies of the same type of control to the form, hold down the Ctrl key and click on the tool. Now the tool remains selected even after you add a control to the form. When you click and drag on the form, the IDE creates a new control at that position and keeps the tool selected so that you can immediately create another control. When you click on the form without dragging the mouse, the IDE adds a new control at that position with a default size. When you are finished adding instances of that control type, click the pointer tool to stop adding new controls.

After you have added controls to a form, there are a couple ways you can make copies of those controls. First, you can select some controls, press Ctrl+C to copy them to the clipboard, and press Ctrl+V to paste them back onto the form at a default location.

Similarly, you can copy and paste controls to other forms. For example, an application might need several dialog boxes that all display similar text in labels, pictures in picture boxes, and OK and Cancel buttons. After you create one dialog box, you can copy and paste its controls onto other dialog boxes to build them more quickly.

The copied controls have the same property values as the originals (except for their names, which must always be unique). If you want to make a series of controls with the same properties, you can make one, set its properties, and then use copy and paste to make the others.

Another way to copy existing controls is to select them, click and drag, and hold down the Ctrl key when you drop them. This makes copies of the controls at the position where you drop them. This technique is particularly useful for making a large array of controls aligned in rows or columns. If you use Ctrl+C and Ctrl+V to copy and paste the controls, they appear in a default location and you must reposition them in a separate step. If you drag and drop while pressing the Ctrl key, you can position the copies as you make them.

Selecting Controls

Telling you to select controls to copy them begs the question, how do you select the controls? Click a control on the form to select it. Hold down the Shift or Ctrl key while clicking to add or remove a control from the selection without removing any other controls from the current selection.

Click and drag over part of the form to select all of the controls that intersect the rectangle you define with the mouse. Hold down the Ctrl key while you click and drag to select controls without removing any currently selected controls from the selection.

Some controls can contain other controls. When you click and drag to select the controls in an area, Visual Basic selects only controls contained in the control on which you initially click. For example, Figure 2-4 shows a form that contains eight buttons. The four buttons on the left are contained in the form itself. The four buttons on the right are contained in a Panel control.

image from book
Figure 2-4: When you click and drag on a form, Visual Basic selects only controls with the same container.

When you click an open piece of form and drag to select an area that covers every control on the form, Visual Basic selects the four buttons on the left and the Panel control because they are all contained in the form itself. It does not select the buttons on the right because they are contained in the Panel control.

When you click on the interior of the Panel control and then drag to surround all of the controls, Visual Basic selects only the four buttons on the right because they are contained in the Panel control.

If you want to select controls from more than one container, you must hold down the Ctrl key and click (or click and drag) to select the controls in several steps. In this case, you might click and drag on the form to select the buttons on the left and the Panel control. Next you would press Ctrl, click in the Panel control, and drag to select the remaining buttons. Unfortunately, clicking on the Panel control deselects it so you need to press Ctrl and click on the Panel again to reselect it. (If you want to select all of the controls on the form, you can also click on the form and press Ctrl+A.)

After you have selected the controls you want to manipulate, you can delete them, copy them, drag them to a new location, modify their common properties using the Properties window, and so forth.

Container Controls

As the previous section mentions, some controls can contain other controls. For example, the GroupBox and Panel controls can hold other controls.

There are several ways you can place a control in a container. If you select the container and then double-click a control’s tool in the Toolbox, Visual Basic places the new control inside the container.

When you select a tool and click and drag inside a container, Visual Basic also places the new control inside the container, whether it is selected or not.

You can also click and drag a Toolbox tool onto the container, or click and drag controls from one part of the form onto the container. If you hold down the Ctrl key when you drop the controls, Visual Basic makes new copies of the controls.

Two common mistakes programmers make with containers is placing a control above a container when they want it inside the container, and vice versa. For example, you can place different controls inside different Panel controls and then hide or display the Panels to show different controls at different times. If a control lies above a Panel but is not inside it, the control remains visible even if the Panel is not.

To tell if a control is inside a container, move the container slightly. If the control also moves, it is inside the container. If the control doesn’t move, it is above the container but not inside it.

Creating Controls at Runtime

Normally, you create controls interactively at design time. Sometimes, however, it’s more convenient to create new controls at runtime. For example, you may want to provide different interfaces for different users. Users with different skill levels or authorizations may need to use different controls to do their jobs. Or you may not know how many pieces of data you will need to display until runtime. 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 runtime.

The following code shows how a program might create a new Label control. 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 and sets its Text property to “Hello World!” The code then adds the label to the current form’s Controls collection.

  Dim lbl As New Label lbl.SetBounds(10, 50, 100, 25) lbl.Text = "Hello World!" Me.Controls.Add(lbl) 

Usually, a label just displays a message so you don’t need to catch its events. Other controls such as buttons and scroll bars, however, are not very useful if the program cannot respond to their events.

There are two approaches you can take to catching a new control’s events. First, you can declare the control’s variable with the WithEvents keyword. Then you can open the form in the code editor, select the variable’s name from the left drop-down list, and select the event from the right drop-down list to give the control an event handler.

The following code demonstrates this approach. It declares variable btnHi at the module level using the WithEvents keyword. When you click the btnMakeHiButton button, its event handler initializes the variable. It sets the control’s position and text, and adds it to the form’s Controls collection. When the user clicks this button, the btnHi_Click event handler executes and displays a message.

  ' Declare the btnHi button WithEvents. Private WithEvents btnHi As Button ' Make the new btnHi button. Private Sub btnMakeHiButton_Click(ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles btnMakeHiButton.Click     btnHi = New Button     btnHi.SetBounds(96, 50, 75, 23)     btnHi.Text = "Say Hi"     Me.Controls.Add(btnHi) End Sub ' The user clicked the btnHi button. Private Sub btnHi_Click(ByVal sender As Object, _  ByVal e As System.EventArgs) Handles btnHi.Click     MessageBox.Show("Hi") End Sub 

This first approach works if you know how many controls you need. Then you can define variables for them all using the WithEvents keyword. If you don’t know how many controls you need to create, however, this isn’t practical. For example, suppose that you want to create a button for each file in a directory. When the user clicks on a button, the file should open. If you don’t know how many files the directory might hold, you don’t know how many variables you might need.

One solution to this dilemma is to use the AddHandler statement to add event handlers to the new controls. The following code demonstrates this approach. When you click the btnMakeHelloButton button, its Click event handler creates a new Button object, storing it in a locally declared variable. It sets the button’s position and text and adds it to the form’s Controls collection as before. Next, the program uses the AddHandler statement to make subroutine Hello_Click an event handler for the button’s Click event. When the user clicks the new button, subroutine Hello_Click displays a message.

  ' Make a new Hello button. Private Sub btnMakeHelloButton_Click(ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles btnMakeHelloButton.Click     ' Make the button.     Dim btnHello As New Button     btnHello.SetBounds(184, 50, 75, 23)     btnHello.Text = "Say Hello"     Me.Controls.Add(btnHello)     ' Add a Click event handler to the button.     AddHandler btnHello.Click, AddressOf Hello_Click End Sub ' The user clicked the Hello button. Private Sub Hello_Click(ByVal sender As System.Object, _  ByVal e As System.EventArgs)     MessageBox.Show("Hello") End Sub 

You can use the same routine as an event handler for more than one button. In that case, the code can convert the sender parameter into a Button object and use the button’s Name, Text, and other properties to determine which button was pressed.

To remove a control from the form, simply remove it from the form’s Controls collection. To free the resources associated with the control, set any variables that refer to it to Nothing. For example, the following code removes the btnHi control created by the first example.

  Me.Controls.Remove(btnHi) btnHi = Nothing 

This code will also remove controls that you created interactively at design time, as well as controls you create during runtime.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net