Home > How-To Library > Controls
Various ways to add/remove items into list box control
**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * **************************************************************** 'To add an item in list box Private Sub Form_Load() List1.AddItem "First" List1.AddItem "Second" List1.AddItem "Third" End Sub 'In real-world applications, you rarely load individual items in this way. Most 'often your data is already stored in an array or in a database, and you have to 'scan the source of your data with a For…Next loop, as in the following code: ' MyData is an array of strings. For i = LBound(MyData) To UBound(MyData) List1.AddItem MyData(i) Next 'If you want to load dozens or hundreds of items, a better approach is to store 'them in a text file and have your program read the file when the form loads. 'This way you can later change the contents of your ListBox controls without 'recompiling the source code: Private Sub Form_Load() Dim item As String On Error GoTo Error_Handler Open "listbox.dat" For Input As #1 Do Until EOF(1) Line Input #1, item List1.AddItem item Loop Close #1 Exit Sub Error_Handler: MsgBox "Unable to load Listbox data" End Sub 'If you want to load many items in a list box but don't want to create an array, 'you can resort to Visual Basic's Choose function, as follows: For i = 1 To 5 List1.AddItem Choose(i, "America", "Europe", "Asia", "Africa", "Australia") Next 'Some special cases don't even require you to list individual items: ' The names of the months (locale-aware) For i = 1 To 12 List1.AddItem MonthName(i) Next ' The names of the days of the week (locale-aware) For i = 1 To 7 List1.AddItem WeekdayName(i) Next ' Remove the first item in the list. List1.RemoveItem 0 ' Quickly remove all items (no need for a For...Next loop). List1.Clear
If you would like to submit your code here please us. Do not forget to mention your name. We are always thankful to each and everyone of you who submitted their code here.