Right guys, I'm really new to this but I'm getting along ok, but I've hit a block.

I need to be able to know how to search a text file in VB for a particular line and then display it.
the files I'm trying to use are set up as: ID, Name, Address, Birthday, Pay-Roll Type
So I need to know how to search the file for the ID number and then display the rest of that line

I can read a file from beginning to end but this I am clueless about, thanks
It's for a system to add, display, update and remove workers

Recommended Answers

All 16 Replies

One easy way is to use a filter as in

Dim alltext() As String = System.IO.File.ReadAllLines(myfilename)
Dim filtered() As String = Filter(text, "12345")

You may have to include the field delimiters (commas, perhaps) in the filter string to prevent matches on the ID string if it should happen to occur in another field.

Another possibility, if the fields are regular and delimited is to open the text file as a data source and use a SQL query to select the records of interest. I can help with that if you want to go the SQL route.

thanks for your help, but I need the User to be able to enter an ID and it isn't the same each time, therefore the code would need adapting each time? The user needs to be able to input the ID in a text box and then locate the corresponding line in the text file

You can replace the string with something like

Dim filtered() As String = Filter(text, txtUserID.text)

If you want to use the file as a data source it can be done using ADO as follows

Imports ADODB

Public Class Form1
    .
    .
    .
 
'assuming the user clicks on btnLogin after entering a userid

   Private Sub login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles login.Click

        Dim con As New ADODB.Connection
        Dim rec As New ADODB.Recordset

        con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myFolder & ";Extended Properties='TEXT;HDR=YES;FMT=DELIMITED'")
        rec.Open("select * from " & myFile & " where ID='" & txtUsedID.Text & "'", con, CursorTypeEnum.adOpenForwardOnly)

        if rec.EOF Then
            'userID was not in the file
        else
            'userID was found
        End If
        
        rec.Close()
        con.Close()

    End Sub

Note the part of the connection string that states HDR=YES. This indicates that the first line of the file contains the names of the fields such as

"ID","Name","Address","Birthday","Pay-Roll Type"
"123","Ferguson, John","704 Hauser St.","1984-01-13","Hourly"
"902","Jefferson, George","East Side","1953-12-20","Salaried"

You can replace the string with something like

Dim filtered() As String = Filter(text, txtUserID.text)

This piece of code won't work, I'm not sure why, it says string cannot be converted to 1 dimensional array of object and Include As Boolean = True, twice.

I used the following code with the sample data I posted above.

Private Sub login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles login.Click

        Dim con As New ADODB.Connection
        Dim rec As New ADODB.Recordset

        con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Temp;Extended Properties=""text;HDR=YES;FMT=Delimited""")
        rec.Open("select * from test.txt where ID='123'", con, CursorTypeEnum.adOpenForwardOnly)

        Do Until rec.EOF
            Debug.WriteLine(rec("ID").Value & " " & rec("Name").Value)
            rec.MoveNext()
        Loop

        rec.Close()
        con.Close()

It worked.

This piece of code won't work, I'm not sure why, it says string cannot be converted to 1 dimensional array of object and Include As Boolean = True, twice.

I'd have to see the actual code that you ran, the exact error message and the contents of the text variables you included in the Filter call.

I use this to check if a name in my file exists.

Dim names As String = ("C:\") 'location of your file
Dim lijst As New System.IO.StreamReader(names)
Dim namelist As String = lijst.ReadToEnd()
lijst.Close()
Dim lines() As String = Split(namelist, vbCrLf)
Dim line As String
For Each line In lines
If line = oldname Then
Label1.Text = line
End If
Next

This won't work unless oldname is the only string on the line. According to your OP, the file format was " ID, Name, Address, Birthday, Pay-Roll Type". In the OP you said you were scanning for "ID". Now it appears you are scanning for "name", at least based on the comparison "if line = oldname Then". If you want to nail this down then I need you to be precise. Also, if you noticed I had suggested

Dim alltext() As String = System.IO.File.ReadAllLines(myfilename)

which reads all of the text file and splits it into an array of lines in one step. This works whether the lines are terminated by vbCrLf or just vbLf. Your way (using a streamreader and a Split) may not work for both cases.

Sorry I was not clear enough, am new at this as well
In my case oldname is a string I read from a TextBox
You do the same with your ID
If you have got the line "ID, Name, Address, Birthday, Pay-Roll Type"
as a string already, you can try this:
Where yourstring is the name you use for "ID, Name, Address, Birthday, Pay-Roll Type"
It reads the total of numbers/letters in your TextBox and gets the same amount from
the left of yourstring where your ID is.

Dim check As String = TextBox1.Text
Dim tl As Integer = TextBox1.TextLength
Dim str as String = Microsoft.VisualBasic.Left(yourstring, tl)
If check = str Then
' whatever you want to do
End If

My mistake. The link in the email took me to the bottom of the thread and I mistook the post from Ge48 as a post from the OP. Anyway, if the OP can please post a sample of the file being searched, and a sample of the text to search for I can post some specific code.

My mistake. The link in the email took me to the bottom of the thread and I mistook the post from Ge48 as a post from the OP. Anyway, if the OP can please post a sample of the file being searched, and a sample of the text to search for I can post some specific code.

Imports System.IO
Public Class Form1
Private Sub BtnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOpen.Click
Dim FileReader As StreamReader
Dim results As DialogResult
results = OpenFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.FileName)
IDFilter.Text = FileReader.ReadToEnd()
FileReader.Close()
End If
End Sub

The text I am trying to search is layed out like so:

094,Frickerman,21 Nicols Road,Canterbury,CT9 3RD,12/12/1981,07 March 2012,Gold
095,Oppern,1 Zion Place,Wye,CT9 1RP,13/01/1974,13 March 2012,Gold

So I want to able to search for 095 and only display:
095,Oppern,1 Zion Place,Wye,CT9 1RP,13/01/1974,13 March 2012,Gold

CurrentlyI can only display the whole text file not the particular line that I want.
Apologies if I'm not being very useful

You wouln't be able to use the ADO method because the fields aren't enclosed in quotes. The address field contains commas and these would be interpreted as field separators. I think the Filter option is your best bet. Read the entire file into a string array then filter on the ID plus a comma. Because this may also match something in the address portion you will still have to do a check on every line in the FIlters array to see if a line starts with the required string.

Dim alltext() As String = System.IO.File.ReadAllLines("d:\temp\test.txt")
Dim lookfor As String = "095" & ","

For Each line As String In Filter(alltext, lookfor)
    If line.StartsWith("095,") Then
        MsgBox("found " & line)
    End If
Next

I create the search string (lookfor) by concatenating an ID value with a comma. You will have to replace "095" with the variable (or textbox.Text object) containing the ID you are looking for. The "Filter" call reduces the array to only those lines containing <lookfor> in any position and the For loop find the line beginning with that value.

You wouln't be able to use the ADO method because the fields aren't enclosed in quotes. The address field contains commas and these would be interpreted as field separators. I think the Filter option is your best bet. Read the entire file into a string array then filter on the ID plus a comma. Because this may also match something in the address portion you will still have to do a check on every line in the FIlters array to see if a line starts with the required string.

Dim alltext() As String = System.IO.File.ReadAllLines("d:\temp\test.txt")
Dim lookfor As String = "095" & ","

For Each line As String In Filter(alltext, lookfor)
    If line.StartsWith("095,") Then
        MsgBox("found " & line)
    End If
Next

I create the search string (lookfor) by concatenating an ID value with a comma. You will have to replace "095" with the variable (or textbox.Text object) containing the ID you are looking for. The "Filter" call reduces the array to only those lines containing <lookfor> in any position and the For loop find the line beginning with that value.

Thank you for your help, do you know how I would adapt this code so I could remove or edit an individual line?

Arrays aren't great when it comes to removing items. Fo9r that you may be better off with a dictionary. It's a tiny bit more trouble to build but it is easier to check if an ID exists. For example:

Private records As New Dictionary(Of String, String)

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click

        Dim key As String

        For Each line As String In System.IO.File.ReadAllLines("d:\temp\test.txt")
            If InStr(line, ",") > 0 Then
                key = line.Substring(0, InStr(line, ",") - 1)
                records(key) = line
            End If
        Next

        If records.ContainsKey("095") Then
            MsgBox("found")
        End If

    End Sub

If you want the key to be an integer then declare as Dictionary(Of Integer, String) and convert the key before addind the new entry.

I've never used dictionarys before, and my whole program is set up to use arrays. thanks for the help though

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.