ListBoxes

 

The ListBox control is used to present a list of items to the user, from which they can select one or more items.

 

In the next couple of examples, we will work with a Listbox named lstFood:

 

 

 

Getting Data into a ListBox

 

To populate a list box at design time, which you would do if the items to be presented are static (not likely to change), you can go to the Items property and click the ellipsis (…) button:

 

This brings up the "String Collection Editor", where you enter the items you want to appear in the list:

These items will then appear in your ListBox at both design-time and run-time:

 

More often than not, however, you will need to populate the list from a file or database table, so you must do so in code. You may prefer to load the list with code even if you are populating it with static items as was done above. To load a ListBox with code, use the Items.Add method. The following statements are equivalent to what we did above:

 

        lstFood.Items.Add("Orange")

        lstFood.Items.Add("Apple")

        lstFood.Items.Add("Pear")

        lstFood.Items.Add("Banana")

 

 

If you want the items in the list to be sorted, you can set the Sorted property to True:

 

With the Sorted propery set to True, the items in the list will be shown in ascending order:

 

 

Referencing Data Items Stored in a ListBox

 

To reference an item in the listbox, you must do so with a valid index of the Items collection, which is an integer between zero and one less than the number of items stored in the ListBox. For example, if there are 4 items in theListBox, a valid index reference is a number between 0 and 3.  To determine the number of items stored in the ListBox, you use the Count property of the Items collection.

 

The code below loops through the listbox and prints its items to the Immediate Window:

 

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

            Debug.Print(lstFood.Items(intX).ToString)

        Next

 

In the screen shot on the right, this code was executed by clicking Button2, causing the items to be listed in the Immediate Window

 

 

Determining Which Items in a ListBox Are Selected

 

With the SelectionMode property, you specify whether a user can select zero, one, or more than one item from the ListBox. Listed below are the effects of the four SelectionMode settings:

 

None will not allow the user to select any items; no items will be highlighted when a user clicks on the listbox.

 

One (default setting) means only one item can be selected from the ListBox.  If the user selects one item, then clicks a different item, the item previously selected is de-selected. 

 

MultiSimple allows the user to select multiple items by first clicking an item, then Ctrl-clicking subsequent items. 

 

MultiExtended does the same thing as "MultiSimple", but also supports selecting a group of contiguous items by allowing the user to click the first item in the group and then Shift-click the last item in the group.

 

 

If SelectionMode is set to One, you can use the SelectedItem or Text property to identify the item selected by the user:

 

        Debug.Print(lstFood.SelectedItem.ToString)

    - or -

        Debug.Print(lstFood.Text)

 

However, if no items are selected or the listbox is empty, the reference to lstFood.SelectedItem.ToString will cause an error. Therefore, it would be best to check SelectedItem.Count:

 

        If lstFood.SelectedItems.Count > 0 Then

            Debug.Print(lstFood.SelectedItem.ToString)

        Else

            Debug.Print("No item is selected.")

        End If

 

This check need not be done if using the Text property. If there is no item selected, the value of the Text property will be an empty string ("").

 

 

If SelectionMode is set to MultiSimple or MultiExtended, you can get the user's selections in one of the two ways shown below.

 

The first way is to loop through all items in the listbox and use the GetSelected method on the current item to see if it is selected:

 

 

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

            If lstFood.GetSelected(intX) Then

                Debug.Print(lstFood.Items(intX).ToString)

            End If

        Next

 

The second way is to loop through the SelectedItems collection:

 

        For intX As Integer = 0 To lstFood.SelectedItems.Count - 1

            Debug.Print(lstFood.SelectedItems(intX).ToString)

        Next

 

 

Pre-Selecting Items in a ListBox with Code

 

Sometimes you may want to pre-select an item or items in code (for example, pre-select the first item as a default).

 

If SelectionMode is set to One, you can use the SelectedIndex property:

 

lstFood.SelectedIndex = 0

 

If SelectionMode is set to MultiSimple or MultiExtended, you can use the SetSelected method:

 

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

            If (Some Condition) Then

                lstFood.SetSelected(intX, True)

            End If

        Next

 

 

Removing Items from a ListBox

 

To remove ALL items from a ListBox, you use the Clear method of the Items collection.  The syntax is:

 

         ListboxName.Items.Clear

 

To remove a particular from the ListBox, use the RemoveAt method.  The RemoveAt method requires you to specify the index value of the element you want to remove:

 

         ListboxName.Items.RemoveAt(IndexValue)

 

For example, the following code removes the second item from the lstFood ListBox:

 

                                lstFood.Items.RemoveAt(1)

 

Removing the Selected Item(s)

 

If SelectionMode is set to One, the selected item can be removed as follows:

 

lstFood.Items.Remove(lstFood.SelectedItem)

 

If SelectionMode is set to MultiSimple or MultiExtended, and you want to remove all the selected items, you should loop through items in REVERSE: i.e., start the loop index at Items.Count – 1 and end the loop index at zero:

 

        For intX As Integer = (lstFood.Items.Count - 1) To 0 Step -1

            If lstFood.GetSelected(intX) Then

                lstFood.Items.RemoveAt(intX)

            End If

        Next

 

Example: Adding and Removing Items with Two ListBoxes

 

A commonly seen action in Windows programs is one in which you have two ListBoxes, where one ListBox contains all of the available items; the other is intended to contain selected items from the list of all available items.  The user adds and removes items by selecting items from the ListBoxes and then clicking an appropriate command button.  Consider the following interface:

 

 

The above interface consists of two ListBoxes, named lstAvail and lstSelected.  Both have their Sorted property set to True and their SelectionMode set to MultiExtended.  The two buttons are named btnAdd and btnRemove.  To move the selected items from lstAvail to lstSelected, the following code was written in btnAdd's Click event:

 

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

 

        For intX As Integer = (lstAvail.Items.Count - 1) To 0 Step -1

            If lstAvail.GetSelected(intX) Then

                lstSelected.Items.Add(lstAvail.Items(intX))

                lstAvail.Items.RemoveAt(intX)

            End If

        Next

 

    End Sub

 

After execution of the above code, the form will look like this:

 

 

Note that the selected items were added to lstSelected and removed from lstAvail.

 

Now suppose the user wants to remove a few items from lstSelected and send them back to lstAvail.  The user selects the items to remove:

 

 

The user then clicks the Remove button, which contains the following code:

 

    Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click

 

        For intX As Integer = (lstSelected.Items.Count - 1) To 0 Step -1

            If lstSelected.GetSelected(intX) Then

                lstAvail.Items.Add(lstSelected.Items(intX))

                lstSelected.Items.RemoveAt(intX)

            End If

        Next

 

    End Sub

 

The form then looks like this:

 

 

Note that the items that were selected in lstSelected were removed from lstSelected and added back to lstAvail. 

 

Download the VB project code for this example here.

 

You'll notice that in the previous example, the code for btnAdd and btnRemove Click events was identical, except for the names of the listboxes in question.  This code could be consolidated into a single Sub that could be placed into a standard module and incorporated into any project where it is needed:

 

    Public Sub MoveListBoxItems(ByVal lstListToAddTo As ListBox, _

                                ByVal lstListToRemoveFrom As ListBox)

 

        For intX As Integer = (lstListToRemoveFrom.Items.Count - 1) To 0 Step -1

            If lstListToRemoveFrom.GetSelected(intX) Then

                lstListToAddTo.Items.Add(lstListToRemoveFrom.Items(intX))

                lstListToRemoveFrom.Items.RemoveAt(intX)

            End If

        Next

 

    End Sub

 

 

With this Sub incorporated into your project, you could use the following code in the btnAdd and btnRemove Click events to call the MoveListBoxItems Sub:

 

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

 

        MoveListBoxItems(lstSelected, lstAvail)

 

    End Sub

 

    Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click

 

        MoveListBoxItems(lstAvail, lstSelected)

 

    End Sub

 

 

Download the VB project code for this example here.

 

 

Implementing "ItemData" for VB.NET ListBoxes

 

In the pre-.NET versions of VB, ListBoxes (and ComboBoxes) had a property array called "ItemData". ItemData was quite useful, because it allowed you to associate a numeric value corresponding to each item in the listbox – so for example, if you had a database lookup table that contained a numeric ID and a description for each entry, you could load that data into a listbox where you would display the descriptions, but also carry the IDs in the ItemData array "behind the scenes".

 

The VB.NET listbox does not have the ItemData property. However, with the .NET ListBox and ComboBox, you can add any object to the Items collection, which is actually a more flexible approach. In order to add an object to the ListBox or ComboBox item collection, you must override the ToString method so that you will have a meaningful entry displayed in the list. How to do this to implement the functionality of ItemData is detailed below:

 

For any project in which you would like to implement the functionality of ItemData for ListBoxes and/or ComboBoxes, you need a class called "MyList" (it can be called whatever you want, but "MyList" is being used here). The code for the MyList class is shown on the right.

 

To add this class to a project, in the IDE, you would go to the Project menu, then choose Add Class, then name it MyList. Then copy and paste this code into the MyList code window. At that point, the functionality of the class and the ItemData property would be available for use.

 

To add an item to the listbox, the syntax would be:

 

    ListBoxName.Items.Add(New MyList(StringToDisplay, IntegerValue))

 

For example, suppose we had a comma-delimited file called "FOOD.TXT" which contained the name of the food along with its calorie count. The data might look like this:

 

"Orange",60

"Apple",80

"Banana",105

 

To read this file and load it into a ListBox (called "lstFood"), you could use the following code:

 

        Dim strFileName As String = _

              My.Application.Info.DirectoryPath & "\FOOD.TXT"

        Dim intFileNbr As Integer

 

        Dim strFoodName As String

        Dim intCalories As Integer

 

        intEmpFileNbr = FreeFile()

 

        FileOpen(intFileNbr, strFileName, OpenMode.Input)

 

        Do Until EOF(intFileNbr)

            Input(intFileNbr, strFoodName)

            Input(intFileNbr, intCalories)

            lstFood.Items.Add(New MyList(strFoodName, intCalories))

        Loop

 

        FileClose(intEmpFileNbr)

 

To refer to the ItemData value for a particular entry in the ListBox, the syntax would be:

      ListBoxName.Items.(Index).ItemData

For example:

            lstFood.Items(2).ItemData

 

To refer to the ItemData value for the selected item in the ListBox, the syntax would be:

            ListBoxName.Items(ListBoxName.SelectedIndex).ItemData

For example:

      lstFood.Items(lstFood.SelectedIndex).ItemData

 

Public Class MyList

 

    Private sName As String

    Private iID As Integer

 

    Public Sub New()

        sName = ""

        iID = 0

    End Sub

 

    Public Sub New(ByVal Name As String, ByVal ID As Integer)

        sName = Name

        iID = ID

    End Sub

 

    Public Property Name() As String

        Get

            Return sName

        End Get

        Set(ByVal sValue As String)

            sName = sValue

        End Set

    End Property

 

    Public Property ItemData() As Integer

        Get

            Return iID

        End Get

        Set(ByVal iValue As Integer)

            iID = iValue

        End Set

    End Property

 

    Public Overrides Function ToString() As String

        Return sName

    End Function

 

End Class

 

 

The CheckedListBox Control

 

The CheckedListBox control is a variation of the standard ListBox control. It works very similarly to the standard ListBox control, with the additional functionality of checkboxes to the left of each item, thus letting the user select desired items by checking them off. The CheckedListBox is pictured below:

 

Note: I recommend setting the CheckOnClick property to True (it is False by default). Setting CheckOnClick to True will cause an item to be checked (or unchecked) when the user clicks on the text portion of the item as well as the checkbox itself (otherwise, the item will be checked only if the user clicks precisely on the checkbox).

 

To determine which items are checked, you can loop through all items in the CheckedListBox and use the GetItemChecked method on the current item to see if it is selected:

 

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

            If chklstFood.GetItemChecked(intX) Then

                Debug.Print(chklstFood.Items(intX).ToString)

            End If

        Next

 

Another way is to loop through the CheckedItems collection:

 

        For intX As Integer = 0 To chklstFood.CheckedItems.Count - 1

            Debug.Print(chklstFood.CheckedItems(intX).ToString)

        Next

 

To check or uncheck an item in code, use the SetItemCheckState method. The method requires the index of the item as well as the enumeration value CheckState.Checked or CheckState.Unchecked.

For example:

chklstFood.SetItemCheckState(2, CheckState.Checked)

chklstFood.SetItemCheckState(4, CheckState.Unchecked)

 

Following is a short demo of the CheckedListBox. A screen-shot is shown below. When the user clicks the "Show Checked Items" button, a label displays the items that were checked.

 

 

The code for the "Show Checked Items" button is as follows:

 

    Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click

 

        Dim strItems As String = ""

        Dim blnFirstCheckedItem As Boolean = True

 

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

            If chklstFood.GetItemChecked(intX) Then

                If blnFirstCheckedItem Then

                    strItems = "Checked Items: "

                    blnFirstCheckedItem = False

                Else

                    strItems &= ", "

                End If

                strItems &= chklstFood.Items(intX).ToString

            End If

        Next

 

        lblItems.Text = strItems

 

    End Sub

 

 

Download the VB project code for this example here.

 

 

*** BONUS MATERIAL ***

 

Remove Duplicate Entries in a ListBox

 

This example incorporates a general Sub procedure that you can use to remove duplicate entries from a listbox.  The code for the Sub is:

 

    Public Sub RemoveListBoxDuplicates(ByVal pobjLB As ListBox)

 

        'REMOVE DUPLICATES FROM LISTBOX

 

        Dim intI As Integer

        Dim intJ As Integer

 

        With pobjLB

 

            For intI = 0 To .Items.Count - 1

 

                For intJ = (.Items.Count - 1) To (intI + 1) Step -1

 

                    If .Items(intJ).ToString = .Items(intI).ToString Then

                        .Items.RemoveAt(intJ)

                    End If

 

                Next

 

            Next

 

        End With

 

    End Sub

 

In the sample program, clicking the "Load ListBox" button loads the listbox with 100 entries, where an entry will be any one of 20 company names selected at random:

 

In the sample program, clicking the "Remove Duplicates" button implements the Sub procedure described above to remove all duplicate entries:

 

 

Download the sample program here.

 

Notes:

You can modify this procedure to work with a ComboBox by modifying the argument in the procedure header as follows:

 

Public Sub RemoveListBoxDuplicates(pobjLB As ComboBox)

 

You can modify this procedure to work with a ListBox, CheckedListBox, OR a ComboBox by modifying the argument in the procedure header as follows:

 

Public Sub RemoveListBoxDuplicates(pobjLB As Control)

 

 

Drag and Drop within a ListBox

 

The next two examples demonstrate how to implement drag and drop with listboxes.

 

The first example implements drag and drop.within one listbox, enabling the user to rearrange the order of the items in the listbox. (Note: The "Sorted" property must be set to False, otherwise the order of items would not change after the drop.)

 

First, item #15 is selected and dragged (the mouse pointer will become a "document" icon) …

 

Then, the mouse is released, "dropping" item #15 in-between items #6 and #7.

 

 

Download the first example here.

 

The second example demonstrates drag and drop between two listboxes. It replicates the functionality of the previously presented "Adding and Removing Items with Two ListBoxes" example, but instead of moving items between the two listboxes with "Add" and "Remove" buttons, you move items between the two listboxes by dragging and dropping.

 

Download the second example here.

 

 

"Search-as-you-type" for an Item in a ListBox

 

This example shows how you can use a textbox in conjunction with a listbox to implement "search-as-you-type" functionality. This example implements the FindString method of the ListBox. (Note: In pre-.NET versions of VB, the "SendMessageByString" API was commonly used to implement this functionality, but the FindString method now accomplishes the same result.)

 

Download it here.

 

 

Show Tooltips for Individual Items in a ListBox

 

This example shows how you can show a tooltip for an individual item in a listbox when you move the mouse over the item. This can be especially useful for long items that do not fully display in the listbox.

 

 

Download it here.