Hour 15


During this hour you will learn

Interacting with Users

This lesson brings you back to the really fun stuff! You deserve congratulations because you got through the hard-core language section of this night-school course. Your only requirement now is to master as many controls as you can so that you can combine the new controls with the programming language tools to build extensive applications.

This hour's lesson takes you on a tour of several new controls. Many of the controls that you have yet to master require some programming. For example, you can't fill a drop-down list box with items until runtime. You can initialize some controls, such as labels, but you can't initialize many of the multivalued controls. The multivalued controls (such as list boxes) require some programming.

Even some of the single-valued controls require some background work on your part if you place them on your form's applications. The check box and option button controls require that your program check their status and maintain order as needed.

Topic 1: Option Buttons and Check Boxes

Although somewhat similar to the command button, option buttons and check boxes require some additional programming to make functional in working applications. The nature of a check box control is that it's on or off like a light switch. When a check box control is selected, it contains a check mark; when not selected, a check box is empty. Option buttons work the same way because they show either an on or off state. Unlike check boxes, however, two or more option buttons in a set can never be on at the same time. Whereas users can click as many check boxes as needed, they can't click multiple option buttons that appear together in the same set on the same form.

FAST TRACK
Have you programmed check boxes and option boxes in earlier versions of Visual Basic? If so, jump to the next topic section, "List Box Controls". Have you worked with all of Visual Basic's list controls in the past? If so, Visual Basic 5 doesn't add much functionality to these controls (except for the DownPicture property, which you should check out on the online help), so you can move onto the next hour's lesson, "Creating VB Forms ".

Overview

Check boxes and option buttons naturally go well together in the same topic section when you learn Visual Basic. Their similarities are more common than other controls. Nevertheless, their slightly different nature requires that you, in the background with program code, make sure that users have checked the appropriate button or box when needed. You'll learn how to place and manage check boxes and option buttons in this topic section. You'll also learn how to use code to test and modify their behavior.

Working with Check Boxes

Remember that a check box is either on or off. The check mark that appears inside the check box indicates its status. Actually, you use check boxes to indicate one of two states that may be on or off but might also represent other kinds of binary possibilities. Check boxes indicate the following kinds of conditions:

A check box's Value property is set to 1 or 0 depending on whether the check box is checked. The descriptive label you use next to the check box lets users know why and when to check the box.

Remember that your application can contain multiple check boxes on the same form. Users can check as many or as few as needed.

Figure 15.1 shows a sample form from the Controls sample application that comes with Visual Basic. In Figure 15.1, both check boxes are clicked, indicating in this case that users want to see the text boldfaced and italicized. If you run this application yourself (look in the VB\Samples\PGuide directory folder for the Controls application), you'll see that as you click the check boxes on and off, the text format changes to reflect the check boxes you've set. When you click a check box, the check mark appears or disappears, depending on the check box's state at the time you click the control.

FIG. 15.1

Two check boxes are checked.

You don't have to click over the actual check box; you can click the check box's caption to mark or unmark the check box.

You don't have to supply a label for the check boxes. The check box Properties window contains a Caption property that you can initialize at design time. Also, Visual Basic takes care of displaying the check mark or removing the check mark as users click the check box. Your only programming requirement is to respond to the check box's Click event (in the Click event procedure) and make the adjustment necessary when the check box changes.

Here's the complete event procedure from Figure 15.1's sample code that executes every time users click the check box labeledBold:

Private Sub chkBold_Click()

' The Click event occurs when the check box changes state.

' Value property indicates the new state of the check box.

    If chkBold.Value = 1 Then     ' If checked.

        txtDisplay.FontBold = True

    Else                          ' If not checked.

        txtDisplay.FontBold = False

    End If

End Sub

The check box's Name property contains chkBold, so the event procedure that executes when users click the check box is named chkBold_Click(). All check boxes have a Value property that contains 1 if the check box is now checked, 0 if the check box isn't checked due to the event's click. This code simple changes the text box's FontBold property to True or False depending on whether users marked the check box.

Table 15.1 lists a few of the check box control's most important properties that you'll work with.

Table 15.1 Important Check Box Properties

Property

Description

Alignment Determines whether the caption appears to the left or right of the check box

Caption Holds the caption displayed next to the check box (you can insert the ampersand, &, before the hot-key letter)

DownPicture Contains a path name of a graphic image to display when users click the check box

Value Holds 0 for unchecked or 1 for checked; you can change this at runtime by assigning a different value to the check box control

The example at the end of this topic section walks you through the creation of an application that uses several check boxes.

Working with Option Buttons

Option buttons work much like check box controls. Each button is a two-state button indicating whether an option is selected or not. Figure 15.2 shows the sample Controls application with two option buttons selected.

FIG. 15.2

Two option buttons are selected.

The primary difference between option buttons and check boxes is that only one option button can be selected at any one time. (The option buttons are said to be mutually exclusive.) Visual Basic takes care of the selection-that is, when your application's users click an option button and then click another option button, Visual Basic deselects the first one and allows only one single button to be selected at one time.

Rarely, if ever, would you need to place only a single option button on a form. When a single option button is selected, users have no way to deselect it. One option button is always selected on a form. If you need a single yes-or-no decision to be added to a form, use a check box control.

Some people call option buttons radio buttons because of their similarity to some car radios, whose push-button channel selector allows for only one station at a time to play.

But wait, doesn't Figure 15.2 show two option buttons selected? The figure shows two sets of option buttons! To be accurate, the figure contains a frame that holds option buttons. Only one option button can be selected within a single frame at any one time. Therefore, you can put multiple sets, or frames, of option buttons on a form, and Visual Basic makes sure that users can select only one option button from a frame at a time.

In Figure 15.2, the frame is the boxed area labeled Operating System that holds option buttons. Therefore, Visual Basic allows only one of these two option buttons to be selected at one time. The three option buttons labeled 486, Pentium, and Pentium Pro appear outside the frame on the form. When option buttons don't reside in a frame but just on the form, every one of those option buttons is considered one set. Therefore, only one of those option buttons can be selected (set to True) at once.

Through the option button's Value property, to which you can assign True or False at runtime or design time, you can set up option buttons so that none are selected. After users select the first one, however, Visual Basic won't let the user deselect all of them again.

Before you add an option button, add a Frame control to your form everywhere you want a set of option buttons. The frame forms the background for the option buttons. In Visual Basic, a frame is known as a container. After you add a frame control that will contain option buttons, you can then add the option buttons. As the example at the end of this topic section will show, you can't add an option button control directly to a frame. After you add an option button to the form, you must cut the option button from the form and then paste the option button onto the frame. You'll add additional option buttons to the frame in this manner until you've completed the form.

Because the Option Button control supports the same properties as the Check Box control, you can refer to Table 15.1 for properties to use with the Option Button control.

Example

This example creates a series of check boxes that display various icons of countries. From the File menu choose New Project to create a new project. Increase the size of the Form window and the form so that the form consumes most of the screen space, fitting comfortably within the Form window while still giving room to the Toolbox.

Follow these steps to create the application:

  1. Double-click the Check Box control to add a check box to the center of the form (see Figure 15.3). (You'll have to move the check box to another location.) Check boxes first appear with the name Check1.

FIG. 15.3

The check box appears in the center of the form.

  1. Change the control's name to chkEngland by entering the new name in the Properties window's Name property. If you don't see the Project window, press Ctrl+R (to choose Project Explorer from the View menu) and adjust the window so that you can see enough properties to work in the window.
  2. Type &England for the check box's Caption property.
  3. Click the Image control.
  4. Click and drag the new Image control to the left of the chkEngland check box. Make the image's outline approximately the same height as the check box and draw a square image.
  5. Name the Image control imgEngland.
  6. Set imgEngland's Visible property to False to hide the image when the program begins.
  7. Click the Image control's Picture property's ellipses to display the Load Picture dialog box. Select the Visual Basic folder (if it isn't already open), the Graphics folder, the Icons folder, and then the Flags folder. Double-click the CTRUK.ICO icon file. (You, in effect, entered \DevStudio\VB\Graphics\Icons\Flags\CTRUK.ICO in the Image control's Picture property to point the property to the icon.) Your Form window should look something like the one in Figure 15.4.

FIG. 15.4

England's picture appears in the Image control.

  1. Double-click the check box to open its Click event procedure. Enter the following code (Visual Basic writes the first and last line for you):
Private Sub chkEngland_Click ()

' Displays the flag if checked

If chkEngland.Value = 1 Then

imgEngland.Visible = True

Else

imgEngland.Visible = False

End If

End Sub

  1. Run the application and click the England check box. The picture of England alternatively appears and disappears due to the If statement in the body of the event procedure.

One simple check box doesn't demonstrate check boxes as well as a series of check boxes would. If you want to add to this lesson's project, you can add additional check boxes and images to the form to display additional foreign country flags.

To add additional check boxes, create five more check boxes and five more image boxes according to the information in Tables 15.2 and 15.3 (the tables include England's check box and image that you've already added). Make certain that you set the Value property of all the check boxes to 0 so that the application begins with no checked boxes.

Table 15.2 Check Box Properties for More Countries

Control Type

Control Name

Value

Caption

Check Box

chkEngland 0

&England
Check Box

chkItaly 0

&Italy
Check Box

chkSpain 0

&Spain
Check Box

chkMexico 0

&Mexico
Check Box

chkFrance 0

&France
Check Box

chkUSA 0

&USA

Table 15.3 Image Properties for More Countries

Control Type

Control Name

Visible

Image*

Image

imgEngland False CTRUK.ICO

Image

imgItaly False CTRITALY.ICO

Image

imgSpain False CTRSPAIN.ICO

Image

imgMexico False CTRMEX.ICO

Image

imgFrance False CTRFRAN.ICO

Image

imgUSA False CTRUSA.ICO

*All pictures come from the directory \DevStudio\VB\Grahics\Icons\Flags

After you assemble these controls into the order and placement shown in Figure 15.5, you're ready to add the event procedures for the controls.

Notice that Figure 15.5 shows the check boxes to the right of the images

FIG. 15.5

The completed form appears with six sets of controls.

Listing 15.1 contains the complete event procedure listing for each control (including England's control set, which you've already added).

Listing 15.1 Checked.bas: Code for the Check Box Control Application

Private Sub chkEngland_Click()

  ' Displays the flag if checked

  If chkEngland.Value = 1 Then

    imgEngland.Visible = True

  Else

    imgEngland.Visible = False

  End If

End Sub

Private Sub chkItaly_Click()

  ' Displays the flag if checked

  If chkItaly.Value = 1 Then

    imgItaly.Visible = True

  Else

    imgItaly.Visible = False

  End If

End Sub

Private Sub chkSpain_Click()

  ' Displays the flag if checked

  If chkSpain.Value = 1 Then

    imgSpain.Visible = True

  Else

    imgSpain.Visible = False

  End If

End Sub

Private Sub chkMexico_Click()

  ' Displays the flag if checked

  If chkMexico.Value = 1 Then

    imgMexico.Visible = True

  Else

    imgMexico.Visible = False

  End If

End Sub

Private Sub chkFrance_Click()

  ' Displays the flag if checked

  If chkFrance.Value = 1 Then

    imgFrance.Visible = True

  Else

    imgFrance.Visible = False

  End If

End Sub

Private Sub chkUSA_Click()

  ' Displays the flag if checked

  If chkUSA.Value = 1 Then

    imgUSA.Visible = True

  Else

    imgUSA.Visible = False

  End If

End Sub

One of the easiest ways to add the code is to copy England's code to the Clipboard, paste the Clipboard below the last event procedure, and then modify the code to fit the next country.

Figure 15.6 shows the running application. You can check more than one check box, as shown in the figure.

FIG. 15.6

Running the program shows multiple check boxes selected at once.

Next Step

Suppose that you showed the preceding example's application to a friend who wanted to see only one flag at a time. Although you can add substantial logic to check for multiple selected check boxes and allow only the most recent check box to remain selected, you can more easily change the check boxes to option buttons (on a frame). Although the application contains only a single set of option buttons, the frame will give you practice in placing controls on a frame.

Follow these steps to convert the application to an option button-based application:

  1. From the Form window, delete all the check boxes. You can click each one and press Delete, or select all of them by "lassoing" them with the mouse (to select all of them) and then press Delete once.
  2. From the View menu choose Code to display the form module code. When you delete controls, Visual Basic doesn't delete the event procedure code associated with those controls but moves such code into the General section of the form module. Highlight all the code (by pressing Ctrl+A, the shortcut key) and press Delete.
  3. Add a Frame control to the form. Size the frame to the approximate area and location of the check boxes that you deleted. You'll place option buttons on the frame now.
  4. Add the six option buttons. For each button, click the Option Button tool and then drag a small rectangle onto the frame at the location of the control. (If you double-click the control to place the control in the center of the form, you'll have to cut and paste the control onto the frame, as mentioned at the end of this topic section.)
  5. Change the frame's name to fraCountries and the frame's Caption to Countries.
  6. Change the option buttons' properties to those in Table 15.4.

Table 15.4 Option Button Properties for the Countries

Control Type

Control Name

Caption

Value

Option button

optEngland England

False
Option button

optItaly Italy

False
Option button

optSpain Spain

False
Option button

optMexico Mexico

False
Option button

optFrance France

False
Option button

optUSA USA

False

  1. Add a new event procedure for each control. Inside England's event procedure, the code will look like this:
Private Sub optEngland_Click()

  ' Displays appropriate flag

  Clear_Flags   ' Calls the Clear_Flags proc

  If optEngland.Value = True Then

    imgEngland.Visible = True

  End If

End Sub

  1. Clear_Flags is a subroutine procedure call. (The Call keyword is optional if you're passing no parameters. Also, you don't use parentheses when you omit Call.) You'll write the Clear_Flags general procedure in step 9.
  2. By using the Clipboard, make five more copies of the code and change the country name in each to finish the option button control code.
  3. Although Visual Basic takes care of setting and resetting option button values when users click the buttons, VB hasn't connected the option buttons in any way to the images. Therefore, each event procedure first clears all images from the form by calling the Clear_Flags() procedure. Type the following code at the top of the module before the first event procedure:

Private Sub Clear_Flags()

imgUSA.Visible = False

imgSpain.Visible = False

imgMexico.Visible = False

imgFrance.Visible = False

imgEngland.Visible = False

imgItaly.Visible = False

End Sub

  1. Visual Basic automatically puts Clear_Flags() in the form module's General section.
  2. 10. Run the application and click different option buttons. As you click one, Visual Basic deselects any other that might already be clicked, and you'll see the appropriate icon thanks to this application's code. Figure 15.7 shows the result of clicking one of the option buttons.

FIG. 15.7

You can select only one option button at a time.

Topic 2: List Box Controls

The List Box and Combo Box controls both work to relieve users from typing. These controls vary from the other controls you've seen because they display multiple values in a list. The controls let you exercise a greater degree of power over the data that users input. Certain kinds of list boxes let users not only select items from a list, but also add items to the list.

Overview

The List and Combo Box controls both operate on a principle that mirrors that of arrays. Therefore, you can use the knowledge you now possess with arrays to understand lists more quickly. Here's an overview of these two important controls:

List Box Controls

The simplest list control is the regular list box. To add a List Box control to your form, clicking the List Box control tool on the Toolbox. The list box gives your users a way to select one or more items from a list of choices. The only requirement is that you initialize the list box's choices with Visual Basic code.

Consider the following code:

Private Sub Form_Load()

  ' Executes when the form loads

  lstFirstList.AddItem "Chicago"

  lstFirstList.AddItem "Dallas"

  lstFirstList.AddItem "Seattle"

  lstFirstList.AddItem "Washington"

  lstFirstList.AddItem "Houston"

  lstFirstList.AddItem "Dayton"

End Sub

When you run your application, the runtime module initially loads the form (or forms, if you have multiple forms). Forms support a Load event that occurs when the form loads. Through the Load and Unload Visual Basic form commands, you can specify exactly when in an application a form is to load or to go away from the application to free up resources. (Hour 16 explains the form Load and Unload events in more detail.)

The form's Load event procedure is a nice place to initialize your form's list box items. If you wait much longer, the list box appears on the form empty. You use the AddItem method to add items to the list box.

A method is kind of like a built-in function. Visual Basic supplies all the methods you'll use. All methods, unlike functions, appear with certain objects. The list box object supports several methods, as do the other controls. You'll always trigger an object's method with this format in your Visual Basic code:

ObjectName.MethodName

The AddItem method is one of the most important list box methods because it adds items to the list. Therefore, if your list box is named lstFirstList, you specify that list box's AddItem method, as shown in the preceding Form_Load() subroutine; add the item you want to put in the list with the AddItem method followed by the item to add. Visual Basic adds the items to the list in the order your code adds the items, unless you change the list box's Sorted property to True, in which case Visual Basic sorts the items in the list alphabetically or numerically as you add items.

The dot (.) notation is common for methods in other languages such as C++. The dot tells the method to operate on the object to the left of the dot. In other words, this line

lstFirstList.AddItem "Seattle"

makes Visual Basic add Seattle to the next item in the list box named lstFirstList.

Sometimes, one of Visual Basic's most difficult aspects is distinguishing between commands, declarations, methods, properties, and controls. Things heat up even more when you learn about classes in Hour 20, "Understanding Classes and Using the Object Browser" (p. xxx). Think of methods as requests that an item makes to itself. lstFirstList.AddItem "Seattle" is saying, "Add an item named Seattle to me." As a list box, lstFirstList knows how to fulfill this request because Visual Basic's designers added this method to the list box's repertoire of methods. (Most controls have their own set of methods available.)


Assuming that a list box control named lstFirstList appears in the center of the form that contains the previous Form_Load() form procedure, the list box will appear, with its city names, like the one shown in Figure 15.8.

FIG. 15.8

The list box holds the added items.

Figure 15.8 shows a label with the caption Destination. Because list boxes don't include such a caption, you must add one when you want to label the list box's contents.

Vertical and possibly horizontal scroll bars appear in the list box if you place the list box control on the form and the height (or width) of the list box isn't sufficient to display all the list items that you add. Also, if the list box can display all the items but the application later adds more items, Visual Basic adds the scroll bars when they become needed.

So far, you've learned only how to display the list box with items inside the list. Although adding items to the list and displaying them is important, your program needs to know which item, if any, users select. The whole purpose of a list box is to let users select an item from a list of choices rather than have to type a value.

When users select an item in the list, the following things happen:

To demonstrate the list box's Text property, consider what would happen if you added a text box to the application shown previously in Figure 15.8. If the text box were named txtCity, the following procedure sends the selected list box item to the text box as soon as users click (to select) an item in the list box named lstFirstList:

Private Sub lstFirstList_Click()

  ' Copy the selected item to the text box

  txtCity.Text = lstFirstList.Text

End Sub

If you were writing such an application, you would want to erase the text box's Text property in the Properties window at design time so that nothing appears in the text box until users select an item. Also, the text box's default Font property almost always needs to be changed because the default Font property setting is too small.

Figure 15.9 shows the result of selecting one of the list box items and sending that selected item to the text box.

FIG. 15.9

The selected item appears in the text box.

List box items have index values that work like array subscripts. The index starts at 0 for the first item and increases. The list box's ListIndex property holds the value of the currently selected list box item. You can, therefore, determine which value is selected. Often, you may fill a list box with values from an array and the one-to-one correspondence to arrays make the selected index item useful for analysis. Other list box methods, such as the RemoveItem method, uses the ListIndex property to remove items you want removed from the list. For example, to remove the third list box item, your program would do this:

lstFirstList.RemoveItem 2

To demonstrate the ListIndex property, Figure 15.10 shows the same application as before with one additional text box that holds the index of the selected item.

FIG. 15.10

The selected item's ListIndex now appears.

The modified lstFirstList_Click()'s code that will send the index to the new text box appears here:

Private Sub lstFirstList_Click()

  ' Copy the selected item to the first text box

  ' Copy the selected index to the second text box

  txtCity.Text = lstFirstList.Text

  txtIndex.Text = lstFirstList.ListIndex

End Sub

Example

Some list boxes provide lists from which users may need to select multiple items. For example, you might display a list box with a list of schools in your area, and users are to select one or more of the schools attended.

The List Box control contains the MultiSelect property. When you set this property to 1 - Simple (as opposed to the default value, 0 - None), users can select multiple values. If you set the MultiSelect property to 2 - Extended, users can Shift+click to select a range of items and Ctrl+click to select disjointed items (just as you can do inside Windows Open dialog boxes).

Figure 15.11 shows an enhanced application from the one the preceding section showed. The enhanced application contains several new text boxes that display Selected when the corresponding list box item is selected, and Not Selected when the list box item isn't selected. The original list box now has its MultiSelect property set to 2 - Extended.

FIG. 15.11

Multiple selections in the list box are now possible.

The list box's click() procedure must be changed to reflect the changed text box format, as shown in Listing 15.2.

Listing 15.2 Clicktb.bas: Extending the Selection in a List Box

Private Sub lstFirstList_Click()

  ' Copy the selected item to the first text box

  ' Copy the selected index to the second text box

  If lstFirstList.Selected(0) Then

    txtChicago.Text = "Selected"

  Else

    txtChicago.Text = "Not Selected"

  End If

  If lstFirstList.Selected(1) Then

    txtDallas.Text = "Selected"

  Else

    txtDallas.Text = "Not Selected"

  End If

  If lstFirstList.Selected(2) Then

    txtSeattle.Text = "Selected"

  Else

    txtSeattle.Text = "Not Selected"

  End If

  If lstFirstList.Selected(3) Then

    txtWashington.Text = "Selected"

  Else

    txtWashington.Text = "Not Selected"

  End If

  If lstFirstList.Selected(4) Then

    txtHouston.Text = "Selected"

  Else

    txtHouston.Text = "Not Selected"

  End If

  If lstFirstList.Selected(5) Then

    txtDayton.Text = "Selected"

  Else

    txtDayton.Text = "Not Selected"

  End If

End Sub

When multiple selections are possible, Visual Basic must create a property array called Selected. In this case, the array ranges from Selected(0) to Selected(5) because six selections appear in the list box. The array values are True or False, depending on the selection. When the program first executes, all the Selected values are False because users haven't had a chance to select an item from the list box. As users select items, more values in the Selected array become True. The list box's Click() procedure updates all six text boxes every time users select another item.

If users deselect an item by clicking a selected item, that item's Selected value goes back to False.

Notice how the labels show a 3-D indented appearance. You can get this same label look by adding a fixed border around the label (change the BorderStyle property to 1 - Fixed Single) and by changing BackStyle from 1 - Opaque to 0 - Transparent so that the form color shows through.

Next Step

Users can't add values to a list box. A list box gains items only when the code inside the application uses the AddItem method to add additional items. Users also can't delete items. The code's RemoveItem method has to do the removal.

Suppose that you needed the application to remove all the items added so far to a list box. Although you could apply the RemoveItem to each list box item, a For...Next loop makes more sense because you can code the loop as follows (given the previous example's list box):

' Removes the first 5 items from the list

For intI = 0 To 5

  lstFirstList.RemoveItem 0

Next intI

When using a For...Next loop, you must keep track of how many items are in the list. Because your code is what adds those items to the list, you should have no trouble keeping track of the count.

If, through programming, you give users a chance to add items to the list (by giving a data-entry text box and a command button that, when clicked, triggers the AddItem method), the list could grow but you can still keep track of the count through a variable that you add to or decrease every time an item goes to or comes off the list.

Fortunately, Microsoft thought of virtually everything. You don't have to really keep track of your list's items because Visual Basic internally keeps a count of the number of items in every list box within the application. The ListCount property keeps a running total of the number of items in the list. ListCount is always one greater than the highest ListIndex because ListIndex starts at 0. Therefore, any time you want to reference the entire list box with a For...Next loop, or any time you need to know the current total of list box items, you can use the ListCount property, as done in this loop:

' Removes all the items from the list

intTotal = lstFirstList.ListCount  ' Save number

For intI = 0 To intTotal

  lstFirstList.RemoveItem 0

Next intI

The list box control's Clear method clears all items immediately without requiring a loop. Therefore, if you want to clear all the contents at once, instead of a range that you'd use a For...Next loop for normally, you can erase the entire list box by doing this: lstFirstList.Clear.

Topic 3: Combo Box Controls

As stated in this lesson's introduction, Visual Basic supports several kinds of list controls. This lesson explores the combo box that comes in three varieties: the drop-down list combo box, the simple combo box, and the drop-down combo box. The best part of these controls is that they're all similar to the list box in the way you initialize and access them from your code. Their primary differences lie in the fact that your users can select and enter data in two of the three combo boxes.

Overview

All three types of combo boxes comes from a single source: the Toolbox's Combo Box control. When you place a Combo Box control on a form, you must then tell Visual Basic, through the combo box's Style property, which combo box you want to use. The default Style when you first place a combo box on a form is 0 - Dropdown Combo. The simplest combo box to begin with is the drop-down list combo box, which is the first of the three that this topic explains.

Throughout this topic, remember that the Sorted property automatically keeps lists sorted for you, alphabetically or numerically, even when users add new values to the list. If you don't specify True for the Sorted property, the list remains unsorted in the order that you put items into it.

The Drop-Down List Combo Box

The drop-down list combo box acts and works just like list boxes, except that list boxes commonly take up more room on a form than a drop-down list combo box. Whereas a list box appears on the form in the size you designate for the list box, the drop-down list combo box always takes a single line on the form. When users click the drop-down list combo box's arrow, however, the drop-down list combo box opens up to display a list of values.

Figure 15.12 shows a form with two drop-down list combo boxes. Before the right combo box was pulled down, both boxes took the same amount of space on the form. Users, by clicking the right drop-down list combo box's arrow, opened the combo box to see the entries and to select one or more values from the combo box.

FIG. 15.12

Drop-down list combo boxes take only a small part of the form until users select a box.

Use drop-down list combo boxes when you need to offer a list of choices but need to save room on the form.

As you can see, a drop-down list combo box displays no text until users select the control. Therefore, you need to make sure that you explain to users, with a label or a message box, exactly what the drop-down list combo box contains.

Use the AddItem method to add entries to the drop-down list combo box just as you did with the list box. The following code adds the six city names to the left control on Figure 15.12:

Private Sub Form_Load()

  ' Add the left-hand combo items

  cboClosed.AddItem "Chicago"

  cboClosed.AddItem "Dallas"

  cboClosed.AddItem "Seattle"

  cboClosed.AddItem "Washington"

  cboClosed.AddItem "Houston"

  cboClosed.AddItem "Dayton"

End Sub

The drop-down list combo box uses the same methods and properties as the list box.

The Simple Combo Box

The simple combo box works like a list box with a text box at the top of the list. In other words, users can select from a list or enter new values in the list. When you add a Combo Box control to a form and set the Style property to 1 - Simple Combo, Visual Basic changes the control so that you can size it the same way you'd size a list box. If you don't give the simple combo box more width and height than is needed to display its values at any time during the application's execution, the simple combo box displays scroll bars to let users scroll through the items.

Figure 15.13 shows the city names listed in a simple combo box control. Your code can load the box with names by using the AddItem method, and users can enter additional items. Be sure to blank out the simple combo box's Text property when you place the control on the form; otherwise, the control's name will appear in place of the users' data-entry space. If you specify a Text property at design time, the simple combo box control uses that value for the default, which users can accept or change.

FIG. 15.13

Users can select a value or enter a new value.

A simple combo box doesn't add users' entries automatically. You must supply code that adds the entries to the combo box.

Although most programmers place simple combo boxes on forms to let users select or enter a new value, if you want to add the users' values to the simple combo box list, you must provide the following code inside the simple combo box's LostFocus () event procedure:

Private Sub cboSCB.LostFocus ()

  cboSCB.AddItem cboSCB.Text

End Sub

The LostFocus () event procedure executes when the control loses the focus, which happens when users click another control or move the focus from the simple combo box with the Tab key. Right as the focus moves to another control, the LostFocus () event procedure executes and the code saves the simple combo box's value entered by users (stored in the Text property) into the simple combo box's list with the AddItem method.

Figure 15.13's application shows a command button because after users enter a new city name, they must shift the focus to another control. Otherwise, the simple combo box won't be able to add the new entry.

The Drop-Down Combo Box

The best of all worlds seems to be the drop-down combo box. The drop-down combo box saves screen space by remaining closed until users select the control. Then, the drop-down combo box opens to display a list of items. Users can select from the list or enter a new value. The Selected, ListCount, and all the usual list box properties work for drop-down combo boxes, so your code can always determine whether users entered a new value or selected an existing one. Unlike the drop-down list combo box, users can add to a drop-down combo box.

Make sure that the combo box's Style property is 0 - Dropdown Combo (the default) when you want to work with a drop-down combo box. To continue using this lesson's familiar city list example, Figure 15.14 again shows the city list-except that the list appears as a drop-down combo box.

FIG. 15.14

Users can select a value or enter a new value.

As with the simple combo box, be sure to clear the drop-down combo box's Text property when you place the control on the form so that nothing appears in the text box at the top of the drop-down combo box. Users can enter new values (adding those values when the focus leaves the control, as done in the previous section), or open the drop-down combo box to display and select from the list.

Example

The ListCmbo sample application project that comes with Visual Basic (in the VB\Samples\PGuide\ListCmbo folder) demonstrates the distinction between a list box and a combo box well. The application displays a list of publishers (you can scroll through the list by clicking the horizontal scroll bar at the bottom of the window).

The nice part of the application is that it switches between a list box and a combo box during the program's execution so that you can see the distinction. Figure 15.15 shows the running application with a list box used for the state abbreviation.

FIG. 15.15

Users select a state from the ordinary list box.

Figure 15.16 shows the same application after users click the option labeled Use Standard Combo Box. Notice that the list remains closed and will remain closed, taking up less room on the form than the list box, until users select the combo box.

FIG. 15.16

Users must open the combo box before seeing additional states.

In neither case can users enter additional states, because all 50 states reside in the list already.

Next Step

Which kind of list do you need? The wide range of choices Visual Basic gives can confuse as much as help. Table 15.5 will help you determine which choice is best for you.

Table 15.5 Determining the Right List Control

Use This Control

If You Want This on the Form

List box

A list from which users can select but not enter values.

Drop-down list combo box

A list that remains closed until users are ready to select values from the list.

Simple combo box

A list that appears on the form and remains open at the size you place the list on the form at design time. Users can select a value or enter a new list value.

Drop-down combo box

A list that remains closed until users are ready to select or enter new list values.

Summary

This lesson showed you how to work with special selection controls. You've learned about the two-choice option buttons and check boxes. Option buttons let users select one value, whereas check boxes let users select zero, one, or more controls.

The list box controls offer several ways to work with data lists. You can add a drop-down list box to display a list of values. The combo boxes let users gain the additional advantage of entering new values into the control.

In Hour 16 you learn how to work with different kinds of application forms. As you already know, forms support properties, and you'll learn the reason for many of those properties in the next hour's lesson.

Hour 15 Quiz

  1. What's the primary difference between an option button and a check box?
  2. What property makes a control, such as the Image control, disappear during program execution?
  3. Why do you have to include a frame on which to put some option buttons?
  4. How do you initialize a list control?
  5. How does a method vary from a function?
  6. What are the differences between the three types of combo boxes?
  7. How do you enable multiple selection of items in a list box?
  8. How does a program determine which item or items users have selected?
  9. Describe the purpose of the Selected list array.
  10. 10. When using a Combo Box control that lets users enter new values, why must you offer at least one additional focus control on the form?

Hour 15 Homework Exercises

  1. Remove the subroutine named Clear_Flags() from the first topic section's Next Step example. Run the application and notice what's now different. You'll have to remove not only the procedure named Clear_Flags(), but also the calls to Clear_Flags() in each of the application's event procedures.
  2. Create a radio front containing option buttons for each radio station you listen to. Create an event procedure for each button that displays the call letters of that station in a text box when you click one of the option buttons.
  3. Write a program that lists your family members in a list box. Include enough members to require scroll bars. Allow for multiple selections and keep the list sorted at all times.
  4. Modify the application you wrote in exercise 3 so that all three kinds of combo boxes appear on the form and display the same data. When one combo box changes-when users enter a new value in the list-reflect that change in the other combo boxes.


© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.