You'll find that this unit is easy because it introduces two new controls that you've seen in many Windows programs, and it also builds upon arrays that you mastered in the previous unit. The check box and option
button controls described here provide
the user with choices of data values and options that the user can select. Unlike list and combo box controls, the check box and option button controls (shown in Figure 12.1's Toolbox window) are perfect controls for
offering the user a limited number of
choices.
Figure 12.1. The check box and option button controls.
Concept: The option button control gives the user the ability to select one item from a list of several items that you display in a series of option button
choices. Visual Basic keeps the user from selecting
more than one option button at a time. The option button's events offer several ways for you to manage the option button selections.
List boxes and combo boxes are perfect controls for
displaying scrolling lists of items from which the user can select and, in the case of combo boxes, add to. Unlike list and combo boxes, option buttons are good to use when you must offer the user a
list of fixed choices that your program knows ahead of
time.
Tip: Think of option buttons as a multiple-choice selection from which the user can choose one item.
Option
buttons are sometimes called radio buttons. Perhaps you're old enough to remember pre-digital car radios that had five or six buttons sticking out with preset statements assigned to each button. At any one time, you could depress one
button because
the radio could play only one station at a time. When you pressed a button, any other button pressed inward immediately clicked out. The buttons were designed so that only one button at a time could be chosen.
Take the time to load CONTROLS.MAK
and press the Next control command button until you see the option buttons shown in Figure 12.2. Try to click more than one option button and you'll see that Visual Basic keeps you from doing so.
Figure 12.2. You may
select only one option button at a time.
Table 12.1 lists the property settings for the option button controls that you can set from within the Property window when you place option buttons on the form. There are several properties that
you've seen before on other kinds of controls.
Property | Description |
Alignment | Either 0 for left justification (the default) or 1 for right justification of the option button's caption. If you choose to left justify, the option button appears to the left of the caption. If you choose to right justify, the option button appears to the right of the caption. |
BackColor | The background color of the option button. This is a hexadecimal number representing one of thousands of possible Windows color values. You'll be able to select from a palette of colors displayed by Visual Basic when you're ready to set the BackColor property. The default background color is the same as the form's default background color. |
Caption | The text that appears in an option button. If you precede any character in the text with an ampersand, &, that character then acts as the option button's access key. |
DragIcon | The icon that appears when the user drags the option button around on the form. (You'll only rarely allow the user to move an option button, so the Drag... property settings aren't usually relevant.) |
DragMode | Either contains 1 for manual mouse dragging requirements (the user can press and hold the mouse button while dragging the control) or 0 (the default) for automatic mouse dragging, meaning that the user can't drag the option button but that you, through code, can initiate the dragging if needed. |
Enabled | If set to True (the default), the option button can respond to events. Otherwise, Visual Basic halts event processing for that particular control. |
FontBold | True (the default) if the Caption is to display in boldfaced characters; False otherwise. |
FontItalic | True (the default) if the caption is to display in italicized characters; False otherwise. |
FontName | The name of the option button caption's style. Typically, you'll use the name of a Windows TrueType font. |
FontSize | The size, in points, of the font used for the command button's caption. |
FontStrikethru | True (the default) if the caption is to display in strikethru letters (characters with a dash through each one); False otherwise. |
FontUnderline | True (the default) if the caption is to display in underlined letters; False otherwise. |
ForeColor | The hexadecimal color code of the caption text's color. |
Height | The height, in twips, of the option button. |
HelpContextID | If you add advanced context-sensitive help to your application, the HelpContextID provides the identifying number for the help text. |
Index | If the option button is part of a control array, the Index property provides the numeric subscript for each particular option button. |
Left | The number of twips from the left edge of the Form window to the left edge of the option button. |
MousePointer | The shape that the mouse cursor changes to if the user moves the mouse cursor over the option button. The possible values are from 0 to 12 and represent a range of different shapes that the mouse cursor can take. (See Lesson 12.) |
Name | The name of the control. By default, Visual Basic generates the names Option1, Option2, and so on as you add subsequent option buttons to the form. |
TabIndex | The focus tab order begins at 0 and increments every time that you add a new control. You can change the focus order by changing the controls' TabIndex to other values. No two controls on the same form can have the same TabIndex value. |
TabStop | If True, the user can press Tab to move the focus to this option button. If False, the option button can't receive the focus. |
Tag | Unused by Visual Basic. This is for the programmer's use for an identifying comment applied to the option button. |
Top | The number of twips from the top edge of an option button to the top of the form. |
Value | Either True or False (the default) indicating whether the option button is selected. |
Visible | True or False, indicating whether the user can see (and, therefore, use) the option button. |
Width | The number of twips wide that the option button consumes. |
Table 12.2 contains a list of
the option button's events that trigger event procedures you can write. Generally, the Click event procedure is the most commonly used so that an application can perform a specific action when the user selects a
particular option button.
Event | Description |
Click | Occurs when the user clicks the option button with the mouse |
DblClick | Occurs when the user double-clicks the mouse over the option button |
DragDrop | Occurs when a dragging operation over the option button completes |
DragOver | Occurs during a drag operation |
GotFocus | Occurs when the option button receives the focus |
KeyDown | Occurs when the user presses a key as long as the KeyPreview property is set to True for the controls on the option button; otherwise, the control gets the KeyDown event |
KeyPress | Occurs when the user presses a key over the option button |
KeyUp | Occurs when the user releases a key |
LostFocus | Occurs when the option button loses the focus |
Stop and Type: Load and run this book's project named TRANSL.MAK. Listing 12.1 contains the code for the project's event procedures. The program allows the user to choose the target language into which
"Good
Morning" is translated. There is room on the form for only one translation, so the option buttons ensure that the user can select one translation at most.
Review: The option button controls enable
you to add choices to the form. The user will be allowed to select from at most one choice by clicking (or tabbing to change the focus and pressing Enter) the option
button of the desired option. By adding code to the option buttons' Click event
procedures, you can respond to the user's choice.
Listing 12.1. The Form_Load() and four option button Click() procedures.
1: Sub Form_Load () 2: ' Make sure that all option buttons are 3: ' False when first displaying the form 4: optFre.Value = 0 5: optIta.Value = 0 6: optSpa.Value = 0 7: optPig.Value = 0 8: End Sub 9: 10: Sub cmdExit_Click () 11: End 12: End Sub 13: 14: Sub optFre_Click () 15: ' Send the French message 16: lblTrans.Caption = "Bonjour" 17: End Sub 18: 19: Sub optIta_Click () 20: ' Send the Italian message 21: lblTrans.Caption = "Buon giorno" 22: End Sub 23: 24: Sub optPig_Click () 25: ' Send the Pig latin message 26: lblTrans.Caption = "oodGa ayDa" 27: End Sub 28: 29: Sub optSpa_Click () 30: ' Send the Spanish message 31: lblTrans.Caption = "Buenos dìas" 32: End Sub
Output: Figure 12.3 shows the TRANSL.MAK screen just after the user selects the Italian option button. The Italian translation appears in the shaded label at the bottom of the screen.
Figure 12.3. The user wants to parla Italiano bene!
Analysis: Listing 12.1 looks a little different from the other listings that
you've seen so far in this book. The listing contains more than one event procedure. As you've gathered by now, a Visual Basic
program consists of lots of event procedures and possibly a (general) procedure. In Lesson 8, you'll learn about other kinds of
procedures that a Visual Basic program may contain.
Although the default Value property for all option buttons is 0, meaning unselected, Visual Basic automatically selects an option button (the one with the lowest TabIndex property value) when
loading the application. Therefore, lines 4 through 7 in
Listing 12.1 set all four option button Value properties to 0 upon loading the form so that there is no option button set until the user selects one. (The four option buttons are named optFre,
optIta, optPig, and optSpa.)
Lines 10 through 12 provide the familiar Exit command button event procedure that terminates the program when the user presses the Exit button.
Lines 14 through 32 complete the code with the four option
button Click event procedures. The user triggers one of the four procedures by selecting one of the four option buttons. The shaded translation label at the bottom of the screen that will hold
the translation is named lblTrans. The four option button
Click event procedures change the Caption property of the lblTrans object to the appropriate translation that matches the option button's caption.
Concept: The check box control works a lot like the option button. You'll place several check boxes on a form; each check box represents a user-selected
choice. Unlike option buttons, the user can select more
than one check box item at a time.
Figure 12.4 contains the check box controls found in this book's CONTROLS.MAK application. If you load and run the program, the check boxes are the fourth
set of controls on which you'll click. As you can see from Figure 12.4, when the user selects a
check box, the check box is marked with an X, indicating a true selection. Two of the three check boxes are selected in Figure 12.4.
Figure 12.4. The check box controls allow for multiple selections.
Note: Although the check box controls in Figure 12.4 don't contain access keystrokes, you can add access keystroke selection to check boxes just as you can for option button controls.
Table 12.3 contains the property values available for check box controls. Most of the properties
are equivalent to the option button properties.
Property | Description |
Alignment | Either 0 for left justification (the default) or 1 for right justification of the check box's caption. If you choose to left justify, the check box appears to the left of the caption. If you choose to right justify, the check box appears to the right of the caption. |
BackColor | The background color of the check box. This is a hexadecimal number representing one of thousands of possible Windows color values. You'll be able to select from a palette of colors displayed by Visual Basic when you're ready to set the BackColor property. The default background color is the same as the form's default background color. |
Caption | The text that appears in a check box. If you precede any character in the text with an ampersand, &, that character then acts as the check box's access key. |
DragIcon | The icon that appears when the user drags the check box around on the form. (You'll only rarely allow the user too move a check box, so the Drag... property settings aren't usually relevant.) |
DragMode | Either contains 1 for manual mouse dragging requirements (the user can press and hold the mouse button while dragging the control) or 0 (the default) for automatic mouse dragging, meaning that the user can't drag the check box but that you, through code, can initiate the dragging if needed. |
Enabled | If set to True (the default), the check box can respond to events. Otherwise, Visual Basic halts event processing for that particular control. |
FontBold | True (the default) if the Caption is to display in boldfaced characters; False otherwise. |
FontItalic | True (the default) if the caption is to display in italicized characters; False otherwise. |
FontName | The name of the check box caption's style. Typically, you'll use the name of a Windows TrueType font. |
FontSize | The size, in points, of the font used for the command button's caption. |
FontStrikethru | True (the default) if the caption is to display in strikethru letters (characters with a dash through each one); False otherwise. |
FontUnderline | True (the default) if the caption is to display in underlined letters; False otherwise. |
ForeColor | The hexadecimal color code of the caption text's color. |
Height | The height, in twips, of the check box. |
HelpContextID | If you add advanced, context-sensitive help to your application, the HelpContextID provides the identifying number for the help text. |
Index | If the check box is part of a control array, the Index property provides the numeric subscript for each particular check box. |
Left | The number of twips from the left edge of the Form window to the left edge of the check box. |
MousePointer | The shape that the mouse cursor changes to if the user moves the mouse cursor over the check box. The possible values are from 0 to 12 and represent a range of different shapes that the mouse cursor can take. (See Lesson 12.) |
Name | The name of the control. By default, Visual Basic generates the names Check1, Check2, and so on as you add subsequent check boxes to the form. |
TabIndex | The focus tab order begins at 0 and increments every time that you add a new control. You can change the focus order by changing the controls' TabIndex to other values. No two controls on the same form can have the same TabIndex value. |
TabStop | If True, the user can press Tab to move the focus to this check box. If False, the check box can't receive the focus. |
Tag | Unused by Visual Basic. This is for the programmer's use for an identifying comment applied to the check box. |
Top | The number of twips from the top edge of a check box to the top of the form. |
Value | Either 0-Unchecked (the default), 1-Checked, or 2-Grayed, indicating whether the check box is selected. |
Visible | True or False, indicating whether the user can see (and, therefore, use) the check box. |
Width | The number of twips wide that the check box consumes. |
Table 12.4 contains the events available for check box controls. As with option buttons, the Click event is generally
the most commonly coded event procedure.
Event | Description |
Click | Occurs when the user clicks the check box with the mouse |
DragDrop | Occurs when a dragging operation over the check box completes |
DragOver | Occurs during a drag operation |
GotFocus | Occurs when the check box receives the focus |
KeyDown | Occurs when the user presses a key as long as the KeyPreview property is set to True for the controls on the check box; otherwise, the control gets the KeyDown event |
KeyPress | Occurs when the user presses a key over the check box |
KeyUp | Occurs when the user releases a key |
LostFocus | Occurs when the check box loses the focus |
Stop and Type: Load and run this book's project named CHECK.MAK. Listing 12.2 contains the code for the project's event procedures. The program allows the user to choose from one
to four special
formatting options for the poem inside the boxed label. The poem can accept any or all four formatting options, so the check box controls enable the user to select one or more of the formatting options.
Review: The check box controls allow more than one selection from the user at a time, unlike the option button controls, which allow only a single option to be selected at a time.
Listing 12.2. The code for the CHECK.MAK project.
1: Sub Form_Load () 2: ' Fill the label with a poem. 3: ' The poem will display initially 4: ' using the default label properties. 5: Dim Newline As String 6: ' The newline sends a carriage return and 7: ' line feed sequence to the poem so that 8: ' the poem can appear as a multiple-line 9: ' poem. 10: Newline = Chr$(13) + Chr$(10) 11: ' Fill the label with the poem 12: ' and concatenate the newline characters 13: lblPoem = "Visual Basic is the best." 14: lblPoem = lblPoem & Newline 15: lblPoem = lblPoem & "It's much better than the rest." 16: lblPoem = lblPoem & Newline 17: lblPoem = lblPoem & "If you ever hear differently," 18: lblPoem = lblPoem & Newline 19: lblPoem = lblPoem & "Give them major misery!" 20: End Sub 21: 22: Sub chkBack_Click () 23: ' Set the poem label's background to Red or white 24: If (lblPoem.BackColor = RED) Then 25: lblPoem.BackColor = WHITE ' Default 26: Else 27: lblPoem.BackColor = RED 28: End If 29: End Sub 30: 31: Sub chkFore_Click () 32: ' Set the poem label's foreground to Green or Black 33: If (lblPoem.ForeColor = GREEN) Then 34: lblPoem.ForeColor = BLACK ' Default 35: Else 36: lblPoem.ForeColor = GREEN 37: End If 38: End Sub 39: 40: Sub chkItal_Click () 41: ' Set the poem label's caption to italicize or not 42: If (lblPoem.FontItalic = True) Then 43: lblPoem.FontItalic = False ' Default 44: Else 45: lblPoem.FontItalic = True 46: End If 47: End Sub 48: 49: Sub chkUnd_Click () 50: ' Set the poem label's caption to underline or not 51: If (lblPoem.FontUnderline = True) Then 52: lblPoem.FontUnderline = False ' Default 53: Else 54: lblPoem.FontUnderline = True 55: End If 56: End Sub 57: 58: Sub cmdExit_Click () 59: End 60: End Sub
[ic:output]Figure 12.5 contains a figure that shows the poem when the user
selects two of the check box options.
Figure 12.5. Selecting two check boxes at the same time.
Analysis: Lines 1 through 20 contain the longest Form_Load()
event procedure that you've seen in this book. The purpose of the procedure is to initialize the label control with the multiline poem. There is no
MultiLine property for labels, so you have to trick Visual Basic into displaying multiple lines inside the
label.
Definition: A control character produces an action, not a text character.
The Chr$() function (called the
character string function or, sometimes, the character function) accepts a number inside its parentheses. The number must come from the ASCII table (Appendix A). Visual Basic converts
that number to its ASCII
character equivalent. ASCII number 13 is the carriage return character and is a special control character that sends the cursor to the beginning of the line, which, in the case of a label, is the beginning column in the
label. ASCII number 10 is
the line feed character that sends the cursor to the next line on the screen. The effect of the concatenated ASCII value of 13 and 10 (line 10) is that a special double control character is created that, when displayed in a
label, sends the cursor
to the beginning of the label's next line.
Note: The poem label's Alignment property is set to 2-Center, so the lines inside the label always display as centered within the label's border.
Lines 13 through 19 then build the multiline poem by concatenating one line and the newline combination string variable to the label's Caption property.
Note: But wait! Lines 13 through 19 don't even mention the Caption property! It appears that the poem's text is being sent to the label itself and not to any property. It turns out that each control has a default property that, unless you specify a different property name, acts as the default property. Therefore, Visual Basic assigns all of the poem's lines to the Caption property in lines 13 through 19 because the Caption property is the default property for labels.
Lines 22 through 56 contain the four check box Click event procedures that set or reset each of the four poem properties described by the check box. The If-Else checks first to see
whether the poem's property is set to the checked value. If so, the true
part of the If sets the property back to its default state. If the property already contains the default value, the Else sets the property to the new state.
As always, the
application contains an Exit command button event procedure in lines 58 through 60 that terminate the program at the user's request.
Concept: Although the user can select only one option button from all the option buttons on the form, there is a way to place multiple sets of option buttons on a form
inside frames. The user can select only
one option button within any frame at a time.
Figure 12.6 shows where the frame control resides on the Toolbox window. The frame control is a holder of other controls. By placing more than one frame on a
form, you can group more than one set of option buttons on the form together.
Figure 12.6. The location of the frame control.
When you want to place several sets of options buttons on a form, be sure to
place more than one frame on the form first. The frames must be large enough to hold as many option buttons as each group requires.
Be careful about placing option buttons when you want to frame them within frame controls. You must draw the
option buttons inside the frame. You can't create the option buttons elsewhere and move them into the frame. For most applications, you
can double-click controls to place them in the middle of the form, and then drag the controls to their final
location and resize them. When placing option buttons inside frames, you must click (not double-click) the option button control on the Toolbox
window and then draw the option button by clicking the mouse inside the frame and dragging the mouse until
you've approximated the option button's size. When you release the mouse button, Visual Basic will draw the option button in the size you drew it.
Stop and Type: Load and run this book's project named
OPTIONS.MAK. Listing 12.3 contains the code for the project's event procedures. The program is similar to the CHECK.MAK application that you saw in the
previous section. Framed groups of option buttons turn selected poem formatting properties on or off.
Review: The frame enables you to group option button controls together. Be sure to place the frame before drawing option button controls inside the frame.
Listing
12.3. The code for the framed option buttons.
1: Sub Form_Load () 2: ' Fill the label with a poem. 3: ' The poem will display initially 4: ' using the default label properties. 5: Dim Newline As String 6: ' The newline sends a carriage return and 7: ' line feed sequence to the poem so that 8: ' the poem can appear as a multiple-line 9: ' poem. 10: Newline = Chr$(13) + Chr$(10) 11: ' Fill the label with the poem 12: ' and concatenate the newline characters 13: lblPoem = "Visual Basic is the best." 14: lblPoem = lblPoem & Newline 15: lblPoem = lblPoem & "It's much better than the rest." 16: lblPoem = lblPoem & Newline 17: lblPoem = lblPoem & "If you ever hear differently," 18: lblPoem = lblPoem & Newline 19: lblPoem = lblPoem & "Give them major misery!" 20: End Sub 21: 22: Sub optGreen_Click () 23: lblPoem.BackColor = GREEN 24: End Sub 25: 26: Sub optItal_Click () 27: lblPoem.FontItalic = True 28: End Sub 29: 30: Sub optNoItal_Click () 31: lblPoem.FontItalic = False 32: End Sub 33: 34: Sub optNoUnd_Click () 35: lblPoem.FontUnderline = False 36: End Sub 37: 38: Sub optRed_Click () 39: lblPoem.BackColor = RED 40: End Sub 41: 42: Sub optUnd_Click () 43: lblPoem.FontUnderline = True 44: End Sub 45: 46: Sub optWhite_Click () 47: lblPoem.BackColor = WHITE 48: End Sub 49: 50: Sub cmdExit_Click () 51: End 52: End Sub
Output: Figure 12.7 contains the OPTIONS.MAK application after the user selects an option in each of the three frames.
Figure 12.7. The framed option buttons allow for multiple
settings.
Analysis: The difficult part of framed option controls is placing the option buttons inside the frames, and even that's not extremely difficult. After you draw the option buttons and
the frames, the usual event
procedures that you've been writing work for the controls.
Lines 22 through 48 contain the Click event procedures that set the poem's label formatting properties.
Concept: By putting one or more similar controls inside a control array, you gain the advantage of writing a
single event procedure that can handle more than one control on the form.
Definition: A control array is a list of controls with the same name.
When you place more than one control of the same control type on a form and assign the same Name property to those controls, you're creating a control array. As with variable arrays, a subscript that begins at 0
differentiates one control from another.
The Index property of each control in the array contains that control's subscript location in the array. If you want to renumber the controls in the array to begin at 1, you can do so by changing the first
zero-based control's Index value to 1.
Note: Each control in a control array must be the same data type.
If there were
five text boxes in a control array named txtBoxes, each individual control would be named txtBoxes(0), txtBoxes(1), txtBoxes(2), txtBoxes(3), and txtBoxes(4).
[ic: Note]As soon as you place a control on the form that has the same name as an existing control, Visual Basic makes sure that you want to begin a control array by issuing the warning message box shown in Figure 12.8. The designers of Visual Basic knew that you may accidentally attempt to place two controls on the same form with the same name, and the message box makes sure of your intent to create a control array. If you select the No command button to the warning message box, Visual Basic returns the second control to a its default name.
Figure 12.8. Visual Basic ensures that you want a control array.
Stop and Type: Load and
run this book's project named CHECK2.MAK. Listing 12.4 contains the code for the project's chkAll_Click() event procedure. The program is similar to the CHECK.MAK application that you
saw in the previous section, except that, instead of four separate
check box event procedures, CHECK2.MAK contains a single check box control array named chkAll.
Review: By placing several controls in a control array, you can reference each control by its subscript
rather than by a different name for each control. Rather than write several event procedures, you need to
write only a single event procedure.
Listing 12.4. The code for control array's event procedure.
1: Sub chkAll_Click (Index As Integer) 2: ' A single Select Case 3: ' handles all check box formats 4: Select Case Index 5: Case 0: 6: ' Set the poem label's background to Red or white 7: If (lblPoem.BackColor = RED) Then 8: lblPoem.BackColor = WHITE ' Default 9: Else 10: lblPoem.BackColor = RED 11: End If 12: Case 1: 13: ' Set the poem label's foreground to Green or Black 14: If (lblPoem.ForeColor = GREEN) Then 15: lblPoem.ForeColor = BLACK ' Default 16: Else 17: lblPoem.ForeColor = GREEN 18: End If 19: Case 2: 20: ' Set the poem label's caption to italicize or not 21: If (lblPoem.FontItalic = True) Then 22: lblPoem.FontItalic = False ' Default 23: Else 24: lblPoem.FontItalic = True 25: End If 26: Case 3: 27: ' Set the poem label's caption to underline or not 28: If (lblPoem.FontUnderline = True) Then 29: lblPoem.FontUnderline = False ' Default 30: Else 31: lblPoem.FontUnderline = True 32: End If 33: End Select 34: End Sub
Analysis: The single Select Case statement handles all four check boxes. There is only one single check box Click() procedure in the entire application even though there are four check boxes. Each check box is
named chkAll, so they all a control array of check boxes and there will be only one event procedure for each event that the programmer wants to program.
Therefore, whenever the user clicks any of the check boxes, the chkAll_Click() event
procedure executes. How does the procedure know which check box triggered the event? Line 1, the event procedure's first line, gives you a good clue.
Visual Basic sends the Index value of the check box that the user clicked to the event procedure.
The parentheses is a mechanism that Visual Basic uses to collect values such as the index to the control array that triggered the event. You'll understand
such parenthetical values in Lesson 8, but until then, be assured that after the chkAll_Click()
procedure executes, an Index variable will contain the subscript of the check box in the control array that the user selected.
The Select Case is a consolidation of Listing 12.2's multiple check box Click() event procedures. As you can see, the
control array saves time and memory because a single event procedure can now handle all the events in the control array.
Find the Bug
Create a form that contains ten option buttons, two sets of five in two frames. Put the ten option buttons inside two control arrays. Label each option button One, Two, Three, Four, and Five. Write two Click event procedures, one for each option button control array, that beep the PC's speaker once for whatever option buttons are selected at that time. In other words, if the user clicks the left frame's Three option button, and the right frame already has the value Two selected, you'll click the speaker five times.