Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleLoad a ListBox from a text file in VB .NET
KeywordsVB.NET, NET, ListBox, text file, load, initialize
CategoriesVB.NET, Controls
 
This program creates a StreamReader to read a text file containing a list of choices. It uses the reader's ReadToEnd method to read the file's contents and calls Split to separate the file's lines. It passes the resulting array to the ListBox's AddRange method to add the lines to the list.

Note that this method will include blank lines in the ListBox if they are present in the file.

 
' Load the ListBox from a file.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    Try
        Dim file_name As String = DataFile()
        Dim stream_reader As New IO.StreamReader(file_name)

        lstAnimals.Items.AddRange(Split(stream_reader.ReadToEnd, _
            vbCrLf))
        lstAnimals.SelectedIndex = 0
        stream_reader.Close()
    Catch exc As Exception
        ' Report all errors.
        MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read " & _
            "Error")
    End Try
End Sub

' Return the data file name.
Private Function DataFile() As String
    Dim file_name As String = Application.StartupPath

    If file_name.EndsWith("\bin") Then file_name = _
        file_name.Remove(file_name.Length - 4, 4)
    file_name &= "\animals.txt"
    Return file_name
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated