DontJudgeMyBadCodePls
DontJudgeMyBadCodePls

Reputation: 23

Writing a text file into an array and reading a particular line VB

I am trying to output a specific line from a text file into an array, where each Button will produce a different line. For example Button1 should output the first line in the text file and Button2 should output the second line in the text file.

Text file:

Red
Blue
Orange
Green

When I press Button1 I get the first line in the TextBox ("Red") however when I press Button2 I still get "Red".

Code

Public Class Form1
    Dim i As Integer
    Dim character As String = ""

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        i = 0
        readfile()
        TextBox1.Text = TextBox1.Text + character
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        i = 1
        readfile()
        TextBox1.Text = TextBox1.Text + character
    End Sub

    Sub readfile()
        Dim SR As New StreamReader("Colours.txt")
        Dim Characters(3) As String
        Do Until SR.Peek = -1
            character = SR.ReadLine
            Characters(i) = character
        Loop
        SR.Close()
    End Sub
End Class

Upvotes: 0

Views: 2519

Answers (1)

Blackwood
Blackwood

Reputation: 4534

I suggest using File.ReadAllLines to read the lines text file into a String array in the form's Load event. Then your Button.Click events can just copy the required line into the TextBox.

Public Class Form1
    Private lines() As String

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        lines = IO.File.ReadAllLines("Colours.txt")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.Text = lines(0)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        TextBox1.Text = lines(1)
    End Sub
End Class

In your question, it's not clear if you want to just store the selected line in the TextBox, or append the line to the TextBox. If you want to append, you can use TextBox1.Text &= lines(0) 'or lines(1) (using &= instead of =) although in that case, you probably also want to add some kind of separator.

Upvotes: 1

Related Questions