Loading combo items from a file

One of the easiest ways to provide something like a find history, or favourites drop down is to load the items from a file. The code below loads items.txt and treats each new line as a new item. Please see 'Saving combo items to a file' for information on saving this information when your program quits.

Private Sub LoadItems()
    On Error GoTo errhandler
    Dim filenum As Integer
    Dim strline As String

    filenum = FreeFile '// Get a free file number
    Open App.Path & "items.txt" For Input As filenum '// open the file

    Do While Not EOF(filenum)
        Line Input #filenum, strline '// read next line
        Combo1.AddItem strline '// load into combo box
    Loop

    Close filenum '// Close the file
    Exit Sub
errhandler:
    If Err = 53 Then '// file not found
        '// create the file
        If CreateFile(App.Path & "items.txt", filenum) Then
            Resume
        End If
    End If
End Sub

Private Function CreateFile(strFile As String, intFileNum As Integer) As Boolean
    On Error Resume Next
    Open strFile For Output As intFileNum '// create the file
    If Err Then
        '// failed
        CreateFile = False
    Else
        CreateFile = True
    End If
    Close intFileNum
End Function

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is anticipated with distaste, performed with reluctance, and bragged about forever.” - Dan Kaminsky