Option Compare Database Option Explicit

Private Sub Form_Load()

' Add preliminary items to the list box. IstFruits.Addltem "Apples" IstFruits.Addltem "Oranges" IstFruits.Addltem "Mangos"

End Sub

Private Sub cmdAddItem_Click()

Dim iCounter As Integer

' Search for a duplicate item.

For iCounter = 0 To (lstFruits.ListCount - 1)

If lstFruits.ItemData(iCounter) = txtlnput.Value Then

MsgBox "Duplicate item. Can't add item."

Exit Sub ' A duplicate was found, exit this procedure.

End If

Next iCounter

' No duplicate found, adding the item. lstFruits.AddItem txtInput.Value

End Sub

A few statements may appear new to you in the preceding program code. First, note the use of the ListCount property in the For loop. The ListCount property contains the number of items in a list or combo box. This number starts at 1, but the lowest number in a list box starts with 0. This is why I subtract 1 from the ListCount property in the For loop statement.

To compare what's in the text box to each item in the list box, I can use the list box's ItemData property, which takes an index (in this case the looping variable) as a parameter and passes back the item's value.

Last but not least is the presence of the Exit Sub statement. This statement is very common with Visual Basic programmers when needing to exit a procedure prematurely. In my case, I want to exit the procedure prematurely (of course, after letting the user know) if a duplicate item is found.

If I choose to use a combo box when accepting input from a user, an additional text box control is not needed because the combo box already contains a text box. In reality a combo box is really two controls: a list box and text box. To accept new input from a user with a combo box, your combo box's LimitToList property must be set to No (the default). When retrieving user input from the combo box, work with its Value or Text properties (which is similar to working with a text box).

0 0

Post a comment