将文本文件写入数组并读取特定行VB

时间:2016-02-28 18:55:13

标签: vb.net

我正在尝试将特定行从文本文件输出到数组中,其中每个Button将生成不同的行。例如,Button1应输出文本文件中的第一行,Button2应输出文本文件中的第二行。

文字档案:

  


  蓝
  橙色
  绿色

当我按Button1时,我会在TextBox(“红色”)中找到第一行,但是当我按下Button2时,我仍然会收到“红色”。

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

1 个答案:

答案 0 :(得分:1)

我建议使用File.ReadAllLines将行文本文件读入表单String事件中的Load数组中。然后,您的Button.Click个活动可以将所需的行复制到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

在您的问题中,您不清楚是否要将所选行存储在TextBox中,或将该行附加到TextBox。如果您想要追加,可以使用TextBox1.Text &= lines(0) 'or lines(1)(使用&=代替=),但在这种情况下,您可能还想添加某种分隔符。