Special-K Special-K - 1 month ago 11
Vb.net Question

Getting strings from a textfile in a combobox, vb.net

Here is my code :
I'm trying to have some value out from a TXT file to a combobox or label but i feel combobox would be easier.

here's my code :

please note, some config.txt will only have 1 value while other 5-6

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IDinFile As String
Dim ID As String

If IO.File.Exists("config.txt") Then

Using StreamReader As New IO.StreamReader("config.txt")
Do
IDinFile = StreamReader.ReadLine
If (IDinFile.IndexOf("7656")) <> -1 Then
ID = IDinFile.Substring(2)
ID = ID.Trim().Remove(ID.Length - 1)
ComboBox1.Items.Add(ID)
Exit Do
End If
Loop Until IDinFile Is Nothing
End Using
End If
End Sub


the file here in .png :
https://i.stack.imgur.com/iYaqP.png

Answer

Re-written the code for you. Problem was wrongly placed Exit Do. Also, its advisable to check the line before entering the loop rather than at the end of the loop.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim IDinFile As String
    Dim ID As String
    Const FILENAME As String = "config.txt"

    If IO.File.Exists(FILENAME) Then
        Using StreamReader As New IO.StreamReader(FILENAME)
            Do While StreamReader.Peek() >= 0
                IDinFile = StreamReader.ReadLine.Trim()
                If (IDinFile.IndexOf("7656")) <> -1 Then
                    ID = IDinFile.Substring(1, IDinFile.Length - 2)
                    ComboBox1.Items.Add(ID)
                End If
            Loop
        End Using
    End If

End Sub