v_kns v_kns - 1 month ago 11
Vb.net Question

Display String From Text File in a Label Box in Visual Basic

So I am trying to make a code where the user inputs an ID number and receives the line of text that the ID corresponds to. I am having trouble with the code as I am unable to display the result (or correct result) in a label box.

For example:

If I type in ID 1, it displays the data that corresponds to ID 2, ID 2 corresponds to ID 3 and ID 3 ends the loop (there are only 3 records in the data currently).

I have included my code below

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Filename = "NamesAndAges.txt"
FileOpen(1, Filename, OpenMode.Input,,,)

Dim ID As Integer
ID = txtSearch.Text

Dim Found As Boolean
Found = False

Do While Not EOF(1) And Found = False

If LineInput(1).Contains(ID) Then
lblDisplaySearch.Text = LineInput(1)
Found = True
Else MsgBox("Not Found")

End If
Loop

FileClose(1)
End Sub


Thanks in advance, would also really appreciate if anyone could explain the code they use as I am still a visual basic beginner.

Answer

Every time you call LineInput(1), it reads a line, so you're reading a line and checking if it contains ID then reading another line and setting lblDisplaySearch.Text to that value.

Try something like this:

Dim line As String

Do While Not EOF(1) And Found = False
    line = LineInput(1)

    If line.Contains(ID) Then
        lblDisplaySearch.Text = line
        Found = True
    Else MsgBox("Not Found")

    End If
Loop
Comments