What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleSave and restore a ComboBox's values from a file
DescriptionThis example shows how to save and restore a ComboBox's values from a file in Visual Basic 6. When the form loads, it reads the file, splits it into lines, and adds each line to the ComboBox. When the form unloads, it writes the ComboBox items into the file.
KeywordsComboBox, save, restore, load data
CategoriesControls, Files and Directories
When the form loads, it calls the GrabFile function to read the file. It splits the file into lines and adds each line to the ComboBox.

Subroutine GrabFile opens the file, reads its entire contents, and closes the file.

' Load the data from last time.
Private Sub Form_Load()
Dim whole_file As String
Dim animals() As String
Dim i As Integer
Dim txt As String


    ' Get the whole file.
    whole_file = GrabFile(App.Path & "\animals.dat")

    ' Break the file into lines.
    animals = Split(whole_file, vbCrLf)

    ' Add the lines to the ComboBox.
    For i = LBound(animals, 1) To UBound(animals, 1)
        txt = Trim$(animals(i))
        If Len(txt) > 0 Then cboAnimals.AddItem txt
    Next i
End Sub

' Return the file's contents.
Private Function GrabFile(ByVal file_name As String) As _
Dim fnum As Integer

    On Error GoTo NoFile
    fnum = FreeFile
    Open file_name For Input As fnum
    GrabFile = Input$(LOF(fnum), fnum)
    Close fnum
    Exit Function

    GrabFile = ""
End Function
When the form unloads, builds a string containing each of the ComboBox's items and calls subroutine WriteFile to save the string in a file.

Subroutine WriteFile opens the file, writes a string, and closes the file. Note that the Print statement ends in a semi-colon so it does not add a carriage return after the string.

' Save the data for next time.
Private Sub Form_Unload(Cancel As Integer)
Dim txt As String
Dim i As Integer

    For i = 0 To cboAnimals.ListCount - 1
        txt = txt & cboAnimals.List(i) & vbCrLf
    Next i
    WriteFile App.Path & "\animals.dat", txt
End Sub

' Write the string into the file.
Private Sub WriteFile(ByVal file_name As String, ByVal txt _
    As String)
Dim fnum As Integer

    fnum = FreeFile
    Open file_name For Output As fnum
    Print #fnum, txt;
    Close fnum
End Sub
Note that in some cases it might be better to load and save these values in the Registry.
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.