Home » Controls » Various ways to add/remove items into list box control
Various ways to add/remove items into list box control
Posted on July 21, 2011
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 |
Enjoy this article?
Filed under: Controls
Leave a comment