How-To... - Add/Remove items to/from a ListBox

Using a ListBox is great for organising data. With the use of headers, it can be a very useful part of a program(open up Windows 'Find Files' box and you'll see a fine example of a ListBox). Below is the source code which shows you how to add items, remove items and clear all items from the ListBox.

Drop a textbox(txtAdd), ListBox(lstAdd), and 3 command buttons(cmdAdd, cmdRemove, cmdClear) onto a new form. Paste the following code into the General Declerations of the Form. You can also download the source-code below.

 

'=====================================
'VB How-To - Example....'
'
'How to Add/Remove items from a ListBox
'
'Full documentated source-code shows you how
'to Add and Remove items from a ListBox and how
'to clear all items from the ListBox...
'
'
'Written by David Cowan(dodgesoft@hotmail.com)
'http://freespace.virgin.net/s.cowan/vbhowto/
'
'=====================================
Private Sub cmdAdd_Click()
'This button click will add an item to the
'Listbox...
'If the textbox is empty then...
If txtAdd.Text = "" Then

    'Display message box...
    MsgBox "Please enter some text!!", 16
       
    '.and place the I-beam into the textbox...
    txtAdd.SetFocus
'Else(if the textbox isn't empty)...
Else
       
    'Add the text to the ListBox...
    lstAdd.AddItem txtAdd.Text
       
    '...and make the last item of the list selected
    'See Below for description...
    lstAdd.ListIndex = lstAdd.ListCount - 1

End If
'ListIndex is a value assigned to each item of the list
'starting from 0.
'
'Listcount is the number of items in the Listbox.
'The reason it is Listcount - 1 is because it counts the
'first item(which is given a LISTINDEX of 0) as 1. This means
'you have to take one of Listcount(otherwise an error would occur).
'
'***NOTE***
'Listcount -1 should only be used with Listindex. If you only
'want to count the number of items, then you would something
'like this :-
'
'i = listbox1.listcount
'
'where i is an numeric variable
End Sub

Private Sub cmdClear_Click()
'Clears the listbox...
lstAdd.Clear
       
End Sub
       
Private Sub cmdRemove_Click()
'Removes the selected item(using the ListIndex)...
lstAdd.RemoveItem lstAdd.ListIndex
'Selects the last item of the list...
lstAdd.ListIndex = lstAdd.ListCount - 1

End Sub

You can download the source code by clicking here


This site is Copyright © 1999 of David Cowan. VB How-To, Dodgesoft and DodgeSoft Productions is Copyright © 1999 of David Cowan. Source-code and programs are copyright of their respective owners. For a messageboard, click here