Search code examples
vb.nettextprogrammers-notepad

Read lines from a text file in VB.NET


I have a text file format:

  *******************************************************************************
    *                              Mitecs Test Plan                               *
    *******************************************************************************

    [PRODUCTN]
    FQA=3F.4.W0,41,1
    RSC=3F.5.W4,36,1
    CFG=3F.9.2J,234,1

    [MASTERREV]
    MTP=3F.R.WM

    [FQA 13]
    FQA=3F.4.W0,41,1
    CFG=3F.9.2J,263,1

    [FQA 14]
    FQA=3F.4.W0,160,1
    CFG=3F.9.2J,315,1

I want to read text and display it in the list box, something like the below:

[PRODUCTN]
[MASTERREV]
[FQA 13]
[FQA 14]

From the above Image

From the above image, when I the select [FQA 14] item in list box 1 and click on the swap button, it should display in the below format in listbox 2 as

Code    Name    Version
160     FQA      3F.4.W0
315     CFG      3F.9.2J

Solution

  • One option is to use a class to hold each entry and override the ToString function to return the heading. Now you can add each entry directly to listbox1 and it will show the title to represent the item. Since each listbox item actually is an object you can cast the selected item as your entry class and read the data from the object. Here's one way to do it:

    Public Class Entry
        Public Property Title As String = ""
        Public Property Data As New List(Of String)
        Public Overrides Function ToString() As String
            Return Title
        End Function
    End Class
    
    Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim sr As New StreamReader("textfile1.txt")
        Do Until (sr.EndOfStream)
            Dim line As String = sr.ReadLine.Trim
            If line.StartsWith("[") Then
                Dim newentry As New Entry
                newentry.Title = line
                Do Until (line = "" OrElse sr.EndOfStream)
                    line = sr.ReadLine.Trim
                    If Not line = "" Then
                        newentry.Data.Add(line)
                    End If
                Loop
                ListBox1.Items.Add(newentry)
            End If
        Loop
    End Sub
    
    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        Dim selectedentry As Entry = DirectCast(DirectCast(sender, ListBox).SelectedItem, Entry)
        ListBox2.Items.Clear()
        For Each datum In selectedentry.Data
            Dim line As String() = datum.Split("=,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
            If line.Count > 2 Then
                ListBox2.Items.Add(line(2) + vbTab + line(0) + vbTab + line(1))
            Else
                ListBox2.Items.Add("   " + vbTab + line(0) + vbTab + line(1))
            End If
        Next
    End Sub