Searching for text in a text file
Hi, this will probably be simple for you guys but, I'm trying to search a text file for a last name, and then display the corresponding info underneath the name from the text file such as phone number, address, etc...After it finds it, it then displays it neatly in a windows form. I can't get it to work though..this is what I have so far.
VB Code:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim input As String 'What I'm searching for
Dim friendFile As System.IO.StreamReader
friendFile = System.IO.File.OpenText("database.txt")
'Use an input box to gain the search string
input = InputBox("Enter the last name of the data you'd like to see.", "Enter Last Name")
'This will only return true if I search for the first name in the text file, but I want it to be able to go down the entire text file
Do
If friendFile.ReadLine = input.ToUpper Then
txtLastName.Text = input.ToUpper
txtFirstName.Text = friendFile.ReadLine()
txtCustNumber.Text = friendFile.ReadLine()
Else : MessageBox.Show("Customer not found.", "Error")
End If
Loop Until friendFile.ReadLine() <> input.ToUpper
End Sub
Ok, I got a little further
OK, I got it to find and display the records from the text file that I want, however, I can't get the error box to display correctly if the user inputs the last name of a customer who doesn't exist.
The problem is that once it finds the record from the text file, it then continues to loop through until the end of the text file, while displaying an error message for every line that doesn't match before and after the correct record. How do I stop the loop once it has found the customer I want? Thanks for any help you may have.
VB Code:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim input As String
Dim friendFile As System.IO.StreamReader
friendFile = System.IO.File.OpenText("database.txt")
input = InputBox("Enter the last name of the data you'd like to see.", "Enter Last Name")
Do Until friendFile.Peek = -1
If friendFile.ReadLine = input.ToUpper Then
txtLastName.Text = input.ToUpper 'Display input in first text box
txtFirstName.Text = friendFile.ReadLine() 'Display first name of customer in second text box
txtCustNumber.Text = friendFile.ReadLine() 'Display customer number in third text box
Else : MessageBox.Show("Customer not found.", "Error")
End If
Loop
End Sub