What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleSave and restore ListBox items when a program stops and starts in Visual Basic 6
DescriptionThis example shows how to save and restore ListBox items when a program stops and starts in Visual Basic 6.
KeywordsListBox, save, restore, Visual Basic 6
CategoriesControls, Software Engineering
This program allows the user to add and remove items from a ListBox. When the user clicks the Add button, the following code uses an InputBox to get a new item and then adds it to the list.
' Add a new item.
Private Sub cmdAdd_Click()
Dim new_value As String

    new_value = InputBox("New value", "New Value")
    If Len(new_value) = 0 Then Exit Sub

    lstFoods.AddItem new_value
End Sub
When the user clicks Remove, the program executes the following code. The code loops through the items in the ListBox and, if an item is selected, removes it from the list.
' Remove the selected item(s).
Private Sub cmdRemove_Click()
Dim i As Integer

    For i = lstFoods.ListCount - 1 To 0 Step -1
        If lstFoods.Selected(i) Then
            lstFoods.RemoveItem (i)
        End If
    Next i
End Sub
The form's Load event handler uses the following code to reload the list's saved items from the Registry. It loops through items named Item1, Item2, and so forth adding each item it finds in the Registry to the list. When it fails to find one of the named items, it exits its loop.
Private Const APP_NAME As String = "SaveRestoreListBox"
Private Const SECTION_NAME As String = "Items"

' Load saved values.
Private Sub Form_Load()
Dim i As Integer
Dim new_value As String


    i = 0
        new_value = GetSetting(APP_NAME, SECTION_NAME, _
            "Item" & Format$(i))
        If Len(new_value) = 0 Then Exit Do

        lstFoods.AddItem new_value
        i = i + 1
End Sub
The form's Unload event handler uses the following code to save the list's current items. It starts by deleting any previously saved items. It protects itself with an On Error statement in case there are no saved items (this happens the first time you run the program).

Next the program loops through the list's items saving them in the Registry with the names Item1, Item2, and so forth.

' Save the list's current items.
' Use On Error in case there are no saved values.
Private Sub Form_Unload(Cancel As Integer)
Dim i As Integer

    ' Remove existing saved items.
    On Error Resume Next
    DeleteSetting APP_NAME
    On Error GoTo 0

    ' Save the items.
    For i = 0 To lstFoods.ListCount - 1
        SaveSetting APP_NAME, SECTION_NAME, "Item" & _
            Format$(i), lstFoods.List(i)
    Next i
End Sub
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.