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, skipping blank lines
KeywordsVB.NET, NET, ListBox, text file, load, initialize, blank lines, blanks
CategoriesVB.NET, Controls
 
The program creates a StreamReader to read a text file containing a list of choices. It uses the reader's ReadLine method to read the file's contents one line at a time. The program trims off any blank spaces from each line and, if the line isn't blank, adds it to the ListBox.
 
' 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)
        Dim line As String

        ' Read the file one line at a time.
        line = stream_reader.ReadLine()
        Do While Not (line Is Nothing)
            ' Trim and make sure the line isn't blank.
            line = line.Trim()
            If line.Length > 0 Then _
                lstAnimals.Items.Add(line)

            ' Get the next line.
            line = stream_reader.ReadLine()
        Loop
        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
 
Alternatively you could grab the file all at once using the ReadToEnd method, use Split, and the loop through the resulting array adding the lines that were non-blank. That might be slightly faster because it does the file read all at once.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated