ComboBoxes

 

ComboBoxes are so-named because they "combine" the features found in both text boxes and list boxes.  ComboBoxes are also commonly referred to as "drop-down boxes" or "drop-down lists".

 

ComboBoxes use many of the same methods as ListBoxes:

·         Use ComboBox.Items.Add("item") to add an item to the ComboBox

·         Use ComboBox.Items.(index).ToString to refer to a particular item in the ComboBox.

·         Use ComboBox.SelectedItem.ToString or ComboBox.Text to refer to the selected item in the ComboBox.

·         Use ComboBox.SelectedIndex = index to set the selected item programatically.

·         Use ComboBox.Items.Clear to remove all items from the ComboBox.

·         Use ComboBox.Items.RemoveAt(index) to remove a particular item from the ComboBox

·         Use ComboBox.Items.Remove(ComboBox.SelectedItem) to remove the selected item from the ComboBox.

 

Note: After a ComboBox is loaded, no item will be pre-selected and the value of SelectedIndex will be -1.

 

There are three ComboBox styles:

·         DropDownList

·         DropDown

·         Simple

 

At design-time, you set the style of the ComboBox with its DropDownStyle property.

 

Of the three ComboBox styles, the one most similar to a ListBox is "DropDownList".  In fact, everything discussed in the previous topic on ListBoxes applies to drop-down style ComboBoxes EXCEPT the following:

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

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

·         Like a ListBox, and unlike the other ComboBox 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.

 

The "DropDown" style of ComboBox operates the same way as the DropDownList, except that the user may type a new value in the text box portion of the ComboBox.  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. If you want to add the new entry to the list portion of the ComboBox, you can do so programatcially.

 

The "Simple" style of ComboBox operates in a manner similar to the DropDown style 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. A "side benefit" of this style is that it has a built-in "search-as-you-type" feature, which will scroll the list down to any matching items as you type in the textbox portion (similar to the "FindString" example given in the previous topic on ListBoxes).

 

ComboBox Demo Program

 

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

 

GroupBox1 has the text "DropDownStyle =  DropdownList" and contains a ComboBox named cboFruit with its DropDownStyle property set to DropdownList. It also contains three buttons, named btnLoadFruitCombo, btnSelFruitProg, and btnShowSelItem. It also contains a checkbox named chkSelItem.

 

GroupBox2 has the text "DropDownStyle = DropDown" and contains a ComboBox named cboStateAbbrev with its DropDownStyle property set to DropDown. It also contains two buttons, named btnLoadStateAbbrevCombo and btnAddNewStateAbbrev.

 

GroupBox3 has the text "DropDownStyle = Simple" and contains a ComboBox named cboStateName with its DropDownStyle property set to Simple. It also contains two buttons, named btnLoadStateNameCombo and btnAddNewStateName.

 

 

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

 

The btnLoadFruitCombo_Click Event

 

In this event, we first clear the cboFruit ComboBox, then manually add five fruit items. We then inform the user that the ComboBox has been loaded.

 

   Private Sub btnLoadFruitCombo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _

   Handles btnLoadFruitCombo.Click

 

        cboFruit.Items.Clear()

 

        cboFruit.Items.Add("Apple")

        cboFruit.Items.Add("Banana")

        cboFruit.Items.Add("Grapefruit")

        cboFruit.Items.Add("Orange")

        cboFruit.Items.Add("Pear")

 

        MsgBox("The fruit combo box hase been loaded.", MsgBoxStyle.Information, "ComboBox Loaded")

 

    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 ComboBox to see the items:

 

 

 

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

 

The btnSelFruitProg_Click Event

 

The purpose of the code behind the btnSelFruitProg button is to show how to select a specific entry from a ComboBox programatically. Given an item to match against, you loop through the entries in the ComboBox 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 SelectedIndex property to that of the matching entry and exit the loop early. In this example, an InputBox prompts the user to enter a Fruit. We then loop through the entries of the ComboBox, comparing the current item entry to the Fruit item entered in the InputBox. If and when the item is found, the SelectedIndex is set accordingly.

 

    Private Sub btnSelFruitProg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelFruitProg.Click

 

        Dim strFruit As String

        Dim blnFound As Boolean

 

        strFruit = InputBox("Please enter the fruit to select (Apple, Banana, Grapefruit, Orange, or Pear).", _

                            "Select Fruit Item Programatically")

 

        If strFruit = "" Then Exit Sub

 

        blnFound = False

 

        For intX As Integer = 0 To cboFruit.Items.Count - 1

            If strFruit.ToUpper = cboFruit.Items(intX).ToString.ToUpper Then

                cboFruit.SelectedIndex = intX

                blnFound = True

                Exit For

            End If

        Next

 

        If Not blnFound Then

            MsgBox(strFruit & " was not found in the list.", MsgBoxStyle.Exclamation, "Item Not Found")

        End If

 

    End Sub

 

Below are screen shots of a sample run:

 

User types "orange" in the InputBox:

 

The item is found in the ComboBox and selected:

 

 

 

The btnShowSelItem_Click  Event

 

The purpose of the code behind the btnShowSelItem button is to demonstrate how to obtain the value of the item that has been selected in the ComboBox, using the SelectedItem property:

 

   Private Sub btnShowSelItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowSelItem.Click

 

        If cboFruit.SelectedIndex = -1 Then

            MsgBox("No item is selected.", MsgBoxStyle.Exclamation, "Show Selected")

        End If

 

        MsgBox("You selected " & cboFruit.SelectedItem.ToString, MsgBoxStyle.Information, "Show Selection")

 

    End Sub

 

 

 

The cboFruit_SelectedIndexChanged Event

 

The purpose of the code behind the cboFruit_SelectedIndexChanged 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 chkSelItem checkbox, then by selecting an item from the cboFruit ComboBox.

 

    Private Sub cboFruit_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _

    Handles cboFruit.SelectedIndexChanged

 

        If chkSelItem.Checked Then

            btnShowSelItem.PerformClick()

        End If

 

    End Sub

 

 

 

Next, we will look at the code dealing with the Dropdown style of the ComboBox.

 

The btnLoadStateAbbrevCombo_Click Event

 

This event loads the cboStateAbbrev ComboBox with U.S. state abbreviations from a comma-delimited sequential file called STATES.TXT. The records in the file contain two fields, the state abbreviation and state name; only the abbreviations are loaded into the ComboBox. As was the case with loading the Fruit ComboBox, 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 btnLoadStateAbbrevCombo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _

    Handles btnLoadStateAbbrevCombo.Click

 

        Dim intStateFileNbr As Integer

        Dim strStateAbbrev As String

        Dim strStateName As String

 

        intStateFileNbr = FreeFile()

 

        FileOpen(intStateFileNbr, My.Application.Info.DirectoryPath & "\STATES.TXT", OpenMode.Input)

 

        cboStateAbbrev.Items.Clear()

 

        Do Until EOF(intStateFileNbr)

            Input(intStateFileNbr, strStateAbbrev)

            Input(intStateFileNbr, strStateName)

            cboStateAbbrev.Items.Add(strStateAbbrev)

        Loop

 

        FileClose(intStateFileNbr)

 

        MsgBox("The state abbreviation combo box hase been loaded.", MsgBoxStyle.Information, "ComboBox Loaded")

 

    End Sub

 

 

The btnAddNewStateAbbrev_Click Event

 

This event shows that with this type of ComboBox, you can type in a new entry in the textbox portion of the ComboBox. However, a new entry is not automatically added to the list portion of the ComboBox. 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 btnAddNewStateAbbrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _

   Handles btnAddNewStateAbbrev.Click

 

        If cboStateAbbrev.Text = "" Then Exit Sub

 

        For intX As Integer = 0 To cboStateAbbrev.Items.Count - 1

            If UCase(cboStateAbbrev.Text) = UCase(cboStateAbbrev.Items(intX).ToString) Then

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

                       "Add New State Abbreviation")

                Exit Sub

            End If

        Next

 

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

 

        ' add the item to the list (and return the index of the newly added item)

        Dim intNewIndex As Integer = cboStateAbbrev.Items.Add(cboStateAbbrev.Text)

        ' select the newly added item

        cboStateAbbrev.SelectedIndex = intNewIndex

 

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

                "Add New State Abbreviation")

 

    End Sub

 

 

 

Finally, we will look at the code dealing with the Simple style of the ComboBox.

 

The btnLoadStateNameCombo_Click Event

 

This event loads the cboStateName ComboBox with U.S. state names from the same comma-delimited sequential file called STATES.TXT. The records in the file contain two fields, the state abbreviation and state name; only the names are loaded into the ComboBox. As was the case with loading the Fruit and state abbreviation ComboBoxes, no item is pre-selected after loading the data. However, since the list portion of this style of ComboBox is visible, you will see the entries after they have been loaded.

 

    Private Sub btnLoadStateNameCombo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnLoadStateNameCombo.Click

 

        Dim intStateFileNbr As Integer

        Dim strStateAbbrev As String

        Dim strStateName As String

 

        intStateFileNbr = FreeFile()

 

        FileOpen(intStateFileNbr, My.Application.Info.DirectoryPath & "\STATES.TXT", OpenMode.Input)

 

        cboStateName.Items.Clear()

 

        Do Until EOF(intStateFileNbr)

            Input(intStateFileNbr, strStateAbbrev)

            Input(intStateFileNbr, strStateName)

            cboStateName.Items.Add(strStateName)

        Loop

 

        FileClose(intStateFileNbr)

 

        MsgBox("The state name combo box has been loaded.", MsgBoxStyle.Information, "ComboBox Loaded")

 

    End Sub

 

 

 

The cmdAddNewStateName_Click Event

 

As was the case with state abbreviation ComboBox, this event shows that with this type of ComboBox, you can type in a new entry in the textbox portion of the ComboBox. However, a new entry is not automatically added to the list portion of the ComboBox. 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 btnAddNewStateName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _

    Handles btnAddNewStateName.Click

 

        If cboStateName.Text = "" Then Exit Sub

 

        For intX As Integer = 0 To cboStateName.Items.Count - 1

            If UCase(cboStateName.Text) = UCase(cboStateName.Items(intX).ToString) Then

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

                       "Add New State Name")

                Exit Sub

            End If

        Next

 

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

 

        ' add the item to the list (and return the index of the newly added item)

        Dim intNewIndex As Integer = cboStateName.Items.Add(cboStateName.Text)

        ' select the newly added item

        cboStateName.SelectedIndex = intNewIndex

 

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

               "Add New State Name")

 

    End Sub

 

 

 

 

Download the project files for the ComboBox demo program here.

 

 

 

Implementing "ItemData" for VB.NET ComboBoxes

 

In the previous topic on ListBoxes, it was discussed that pre-.NET versions of the VB ListBox and ComboBox had a useful property array called "ItemData" that allowed you to associate a numeric value with each item in the list. While the VB.NET ListBox and ComboBox do not have the ItemData porperty, you can instead add an object to the ListBox or ComboBox Item collection, which is a more flexible approach. The previous topic showed how to implement "ItemData" via a class called "MyList". This next sample program uses that approach in a variation on the "DropDownList" example given above, which loads the fruit and their associated calorie count into the ComboBox, and displays this value when you click the "Show Selected Item" button:

 

 

Download the project files for this example here.

 

 

Extend the Width of the Drop-Down List

 

By default, the width of the drop-down list portion of a ComboBox is the same width as the textbox portion. You can specify your own value in the DropDownWidth property of the ComboBox (however, you would be "guessing" at the desired size if you did not know how wide, in pixels, the widest item in the list is). This example implements a function that enables you to set up the ComboBox 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 ComboBox receives focus. In the screen-shot below, the user typed "something" in the first textbox, then just tabbed over to the Fruit ComboBox.

 

 

Download the project files for this example here.

 

 

 

 

Search-As-You-Type

 

This example shows how you implement "search-as-you-type" functionality with a ComboBox. As you type characters in the textbox portion of the ComboBox, the first item in the list that starts with those characters will be selected. To implement this, you set the "AutoComplete" properties of the ComboBox. In this example, the AutoCompleteMode was set to SuggestAppend, and the AutoCompleteSource was set to ListItems:

 

 

 

 

In the screen shot below, having loaded the ComboBox with the list of US States, as soon as the user types "t" in the box, "TENNESSEE" is selected, and list shows the states that begin with "T":

 

 

Since you want the user to be able to type in the textbox portion, the DropDownStyle CANNOT be "DropDownList" (it must be "DropDown"). So what if you want to restrict the user's selection to items that are in the list, but still want to allow them to use the "search-as-you-type" functionality? After wrestling with this problem for a while, I found it could be done with the Validating event. This sample program uses that event to make sure a valid value has been entered in the ComboBox before moving on to the next control. If the entry is not valid, I show the message shown below:

 

 

Download the project files for this example here.