CodeItBetter Programming Another VB Programming Blog

Various ways to add/remove items into list box control

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
'Controls - Various ways to add/remove items into list box control
'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

Related posts:

  1. How to move multiple items from one List Box to another List Box/Combo Box
  2. How to Drag/Move items from one List Box to another List Box
  3. How to enable the user to drag and drop items between two list boxes
  4. How to remove duplicates from list box (in two ways)
  5. How to load a text file into list box for a given file name
  6. How to add item to a multi-column Listbox (in two ways)
  7. How to Sort Numbered Items In List Box/Combo Box
  8. How to load items from a Listbox into an array
  9. How to remove an item from List box
  10. How to sort a list of random numbers in List box at run time

Filed under: Controls Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.