Combo Boxes

 

Combo boxes are so-named because they "combine" the features found in both text boxes and list boxes.  Combo boxes are also commonly referred to as "drop-down boxes" or "drop-down lists". There are three combo box styles:

 

            0 – Drop Down Combo

            1 – Simple Combo

            2 – Drop Down List

 

At design-time, you set the style of the combo box with its Style property.

 

 

Of the three combo box styles, the one most similar to a ListBox is "2 -  Drop-Down List".  In fact, everything discussed in the last several pages regarding ListBoxes applies to drop-down style combo boxes EXCEPT the following:

 

·         The combo box displays the selected item in the text box portion of the combo box.  The ListBox portion of the combo box remains hidden until the combo box receives focus and the user clicks the down arrow on the text box.

 

·         You can change the width of a drop-down combo box, but not its height.

 

·         Like a ListBox, and unlike the other combo box styles, the user can only select a value that is in the list – they cannot type in a new value.  However, if the user does press a keyboard key, the closest item in the list alphabetically will be selected (i.e., if the user types the letter "B", and the word "Banana" is in the list, then "Banana" will be selected).

 

·         Multiple selections cannot be made.  Only one item may be selected from the list.

 

·         Unlike a ListBox, VB does not automatically pre-select the first value from a combo box.  Therefore, the initial value of the ListIndex property is –1.  If you do not pre-select a value in code (say in the Form_Load procedure), then be sure to check the ListIndex property for a value of –1 when you check to see which item the user selected.

 

 

The "0 – Drop Down Combo" style of combo box operates the same way as the Drop Down List, except that the user may type a new value in the text box portion of the combo box.  Please note that if the user types a non-list value, this value is NOT automatically added to the list, and the value of ListIndex would be –1.  You should check the Text property to access the user's selection or entry.

 

The "1 – Simple Combo" style of combo box operates in a manner similar to the Drop Down Combo in that the user can either select an item from the list or type a new entry. The difference is that the list does not drop down – like a ListBox, you determine the height of the list portion at design-time.  This is the only combo-box style that allows you to adjust the height of the list portion.

 

Combo Box Demo Program

 

A sample program to demonstrate the three combo box styles will now be presented. The form at design-time is shown below:

 

 

Frame1 has the Caption 'Style "2 – Dropdown List"' and contains a combo box named cboFood with its Style property set to 2 – Dropdown List. It also contains three command buttons, named cmdLoadFoodCombo, cmdSelect, and cmdDetermine. It also contains a checkbox named chkAuto.

 

Frame2 has the Caption 'Style "0 – Dropdown Combo"' and contains a combo box named cboStateAbbrev with its Style property set to 0 – Dropdown Combo. It also contains two command buttons, named cmdLoadStateAbbrevCombo and cmdAddNewAbbrev.

 

Frame3 has the Caption 'Style "1 – Simple Combo"' and contains a combo box named cboStateName with its Style property set to 1 – Simple Combo. It also contains two command buttons, named cmdLoadStateNameCombo and cmdAddNewName.

 

We will first look at the code dealing with the Dropdown List style of the combo box.

 

The cmdLoadFoodCombo_Click Event

 

In this event, we first clear the cboFood combo box, then manually add three food items along with their calorie count in the corresponding ItemData property. (See the earlier discussion "Getting Data into a Listbox" for more detail.) We then inform the user that the combo box has been loaded.

 

Private Sub cmdLoadFoodCombo_Click()

    

    cboFood.Clear

   

    cboFood.AddItem "Orange"

    cboFood.ItemData(cboFood.NewIndex) = 60

    cboFood.AddItem "Apple"

    cboFood.ItemData(cboFood.NewIndex) = 80

    cboFood.AddItem "Banana"

    cboFood.ItemData(cboFood.NewIndex) = 105

 

    MsgBox "Food combo box has been loaded.", _

           vbInformation, _

          "Combo Box Demo"

 

End Sub

 

Note: When you run the sample application and click this button, you will not initially see these items, because we are not pre-selecting any item:

 

 

You have to click the down arrow on the combo box to see the items:

 

 

 

If you wanted to pre-select an item in the combo box, you would set the ListIndex property to the index of the desired entry. For example, the statement cboFood.ListIndex = 0 would pre-select the first item in the box.

 

The cmdSelect_Click Event

 

The purpose of the code behind the cmdSelect button is to show how to select a specific entry from a combo box in code. Given an item to match against, you loop through the entries in the combo box until you either find a matching entry or you go through the entire list without finding the entry. If you find the desired entry, you set the ListIndex property to that of the matching entry and exit the loop early. In this example, an InputBox prompts the user to enter a food. We then loop through the entries of the combo box, comparing the current List entry to the food item entered in the InputBox. If and when the item is found, the ListIndex is set accordingly.

 

Private Sub cmdSelect_Click()

 

    Dim strFood     As String

    Dim intX        As Integer

    Dim blnFound    As Boolean

   

    strFood = InputBox("Please enter the food to select (apple, orange, or banana).", _

                       "Combo Box Demo - Select with Code")

                       

    If strFood = "" Then Exit Sub

   

    blnFound = False

   

    For intX = 0 To cboFood.ListCount - 1

        If UCase$(cboFood.List(intX)) = UCase$(strFood) Then

            cboFood.ListIndex = intX

            blnFound = True

            Exit For

        End If

    Next

 

    If Not blnFound Then

        MsgBox "Item was not found in the list.", _

               vbExclamation, _

               "Combo Box Demo"

    End If

 

End Sub

 

Below are screen shots of a sample run:

 

User types "apple" in the InputBox:

 

The item is found in the combo box and selected:

 

 

Note: This exact same technique can be used to match on an ItemData entry in the list. For example, the code could be modified to accept a number, then you could loop through the combo box entries looking for an ItemData entry that matched that number. The check could be done with a statement similar to If cboFood.ItemData(intX)) = MyNumericEntry Then ...

 

The cmdDetermine_Click Event

 

The purpose of the code behind the cmdDetermine button is to show how you determine and obtain the value of the item that has been selected in the combo box. Again, our friend the ListIndex property is used. The value of the text portion of the selected item is given by ComboBoxName.List(ComboBoxName.ListIndex). If there is a corresponding ItemData item, that value is given by ComboBoxName.ItemData(ComboBoxName.ListIndex).

 

Private Sub cmdDetermine_Click()

 

    If cboFood.ListIndex = -1 Then

        MsgBox "There is no item currently selected.", _

               vbInformation, _

               "Combo Box Demo"

        Exit Sub

    End If

   

    MsgBox "You have selected " & cboFood.List(cboFood.ListIndex) & "." & vbNewLine _

         & "It has " & cboFood.ItemData(cboFood.ListIndex) & " calories.", _

           vbInformation, _

           "Combo Box Demo"

   

End Sub

 

 

The cboFood_Click Event

 

The purpose of the code behind the cboFood_Click event is to show that the value of the selected items can be obtained as soon as the user selects it from the drop-down list. This behavior can be examined by first checking the chkAuto checkbox, then by selecting an item from the cboFood combo box.

 

Private Sub cboFood_Click()

    If chkAuto.Value = vbChecked Then

        Call cmdDetermine_Click

    End If

End Sub

 

 

Next, we will look at the code dealing with the Dropdown Combo style of the combo box.

 

The cmdLoadStateAbbrevCombo_Click Event

 

This event loads the cboStateAbbrev combo box with U.S. state abbreviations from a comma-delimited sequential file called STATES.DAT. The records in the file contain two fields, the state abbreviation and state name; only the abbreviations are loaded into the combo box. No values are added to the optional ItemData property array of the combo box. As was the case with loading the food combo box, no item is pre-selected after loading the state abbreviations, so you will not see the entries until you click the arrow on the drop-down box.

 

Private Sub cmdLoadStateAbbrevCombo_Click()

 

    Dim intStateFileNbr As Integer

    Dim strBS           As String

    Dim strStateAbbrev  As String

    Dim strStateName    As String

   

    strBS = IIf(Right$(App.Path, 1) = "\", "", "\")

    intStateFileNbr = FreeFile

   

    Open (App.Path & strBS & "STATES.DAT") For Input As #intStateFileNbr

   

    cboStateAbbrev.Clear

   

    Do Until EOF(intStateFileNbr)

        Input #intStateFileNbr, strStateAbbrev, strStateName

        cboStateAbbrev.AddItem strStateAbbrev

    Loop

 

    Close #intStateFileNbr

 

    MsgBox "State abbreviation combo box has been loaded.", _

           vbInformation, _

          "Combo Box Demo"

 

End Sub

 

The cmdAddNewAbbrev_Click Event

 

This event shows that with this type of combo box, you can type in a new entry in the textbox portion of the combo box. However, a new entry is not automatically added to the list portion of the combo box. If you wish to do this, you must do so with code, as the code in this event procedure demonstrates. When the "Add New Item to List" button is clicked, this code runs to first check that the item is not already in the list, and if not, adds it.

 

Private Sub cmdAddNewAbbrev_Click()

 

    Dim intX    As Integer

   

    If cboStateAbbrev.Text = "" Then Exit Sub

   

    For intX = 0 To cboStateAbbrev.ListCount - 1

        If UCase$(cboStateAbbrev.Text) = UCase$(cboStateAbbrev.List(intX)) Then

            MsgBox "Item '" & cboStateAbbrev.Text & "' is already in list.", _

                   vbExclamation, _

                   "Combo Box Demo"

            Exit Sub

        End If

    Next

   

    ' if we get here, the item entered in text portion is not in the list

    cboStateAbbrev.AddItem cboStateAbbrev.Text

    MsgBox "Item '" & cboStateAbbrev.Text & "' has been added to the list.", _

           vbExclamation, _

           "Combo Box Demo"

 

End Sub

 

 

 

 

Finally, we will look at the code dealing with the Simple Combo style of the combo box.

 

The cmdLoadStateNameCombo_Click Event

 

This event loads the cboStateName combo box with U.S. state names from the same comma-delimited sequential file called STATES.DAT. The records in the file contain two fields, the state abbreviation and state name; only the names are loaded into the combo box. No values are added to the optional ItemData property array of the combo box. As was the case with loading the food and state abbreviation combo boxes, no item is pre-selected after loading the data. However, since the list portion of this style of combo box is visible, you will see the entries after they have been loaded.

 

Private Sub cmdLoadStateNameCombo_Click()

 

    Dim intStateFileNbr As Integer

    Dim strBS           As String

    Dim strStateAbbrev  As String

    Dim strStateName    As String

   

    strBS = IIf(Right$(App.Path, 1) = "\", "", "\")

    intStateFileNbr = FreeFile

   

    Open (App.Path & strBS & "STATES.DAT") For Input As #intStateFileNbr

   

    cboStateName.Clear

   

    Do Until EOF(intStateFileNbr)

        Input #intStateFileNbr, strStateAbbrev, strStateName

        cboStateName.AddItem strStateName

    Loop

 

    Close #intStateFileNbr

 

    MsgBox "State name combo box has been loaded.", _

           vbInformation, _

          "Combo Box Demo"

 

End Sub

 

 

The cmdAddNewName_Click Event

 

As was the case with state abbreviation combo box, this event shows that with this type of combo box, you can type in a new entry in the textbox portion of the combo box. However, a new entry is not automatically added to the list portion of the combo box. If you wish to do this, you must do so with code, as the code in this event procedure demonstrates. When the "Add New Item to List" button is clicked, this code runs to first check that the item is not already in the list, and if not, adds it.

 

Private Sub cmdAddNewName_Click()

 

    Dim intX    As Integer

   

    If cboStateName.Text = "" Then Exit Sub

   

    For intX = 0 To cboStateName.ListCount - 1

        If UCase$(cboStateName.Text) = UCase$(cboStateName.List(intX)) Then

            MsgBox "Item '" & cboStateName.Text & "' is already in list.", _

                   vbExclamation, _

                   "Combo Box Demo"

            Exit Sub

        End If

    Next

   

    ' if we get here, the item entered in text portion is not in the list

    cboStateName.AddItem cboStateName.Text

    MsgBox "Item '" & cboStateName.Text & "' has been added to the list.", _

           vbExclamation, _

           "Combo Box Demo"

 

End Sub

 

 

 

Download the project files for the combo box demo program here.

 

 

 

*** BONUS MATERIAL ***

ComboBox Procedures

Presented below are several examples of how to extend the functionality of the combobox.

 

Extend the Number of Items Displayed

 

By default, when you click the drop-down arrow of a combo box, VB will display a maximum of eight items. This example shows how you can set up the combo box to display as many items as you want when the drop-down arrow is clicked.

 

 

Download the project files for this example here.

 

 

Extend the Width of the Drop-Down List

 

By default, the drop-down list of a combo box is the same width as the combo box itself. This example shows how you can set up the combo box so that the width of the drop-down list is as wide as the widest item in the list.

 

 

Download the project files for this example here.

 

 

Automatically Drop Down the List when ComboBox Receives Focus

 

This example shows how you can automatically display the drop-down list (as opposed to having the user click the drop-down arrow) when the combo box receives focus.

 

 

Download the project files for this example here.

 

 

Creating a "Multi-Select" Checkbox-ComboBox

 

This example shows how you can simulate a combo box where the items in the drop-down list have checkboxes, enabling you to make multiple selections. The multiple selections are shown comma-delimited in the text portion of the combo box. This example does not actually use a combo box – the text portion is actually a picture box containing a label and a graphical-style command button for the drop-down arrow. When the command button is clicked, a checkbox-style listbox is displayed.

 

 

In this sample program, when you click the "Show Selected Items" button, a message box is displayed, showing both the items that were selected, as well as the corresponding ItemData items, both "as is" as well as enclosed in quotes.

 

 

Download the project files for this example here.

 

 

Search-As-You-Type ComboBox

 

This example shows how you implement "search-as-you-type" functionality with a combo box. As you type characters in the textbox portion of the combo box, the first item in the list that starts with those characters will be selected. In the screen shot below, as soon as the user types "o" in the box, "onion rings" is selected. This example limits the user to items contained in the list.

 

 

Download the project files for this example here.

 

 

Search-As-You-Type ComboBox (Enhanced Database Example)

 

This example extends the "search-as-you-type" functionality demonstrated in the previous example by using database lookups, and this implementation does NOT limit the user to the items contained in the list. If the user types in an item that is not already in the list and clicks the Refresh button, the new item will show up the next time the list is dropped down (i.e., the new item will be inserted into the database table).

 

 

A couple of options can be used to modify the behavior of the combo box. You can choose to have the program load items based on the first letter typed (i.e., as shown in the screen shot above, when you type the letter "B",  load only the companies that start with the letter "B"). This option makes sense when you are selecting values from a large database table. Alternatively, you can choose to have the program load all values from the database table at once. That option would be suitable for smaller tables.

 

Also, you can choose whether or not you want the drop-down box to be displayed as soon as focus is moved to the combo box.

 

 

Download the project files for this example here.