我正在尝试将特定行从文本文件输出到数组中,其中每个Button
将生成不同的行。例如,Button1
应输出文本文件中的第一行,Button2
应输出文本文件中的第二行。
文字档案:
红
蓝
橙色
绿色
当我按Button1
时,我会在TextBox
(“红色”)中找到第一行,但是当我按下Button2
时,我仍然会收到“红色”。
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
答案 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)
(使用&=
代替=
),但在这种情况下,您可能还想添加某种分隔符。