将文本文件写入数组并读取特定行 VB [英] Writing a text file into an array and reading a particular line VB
问题描述
我试图将文本文件中的特定行输出到数组中,其中每个 Button
将生成不同的行.例如 Button1
应该输出文本文件中的第一行,Button2
应该输出文本文件中的第二行.
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.
文本文件:
红色
蓝色
橙色
绿色
Red
Blue
Orange
Green
当我按下 Button1
时,我得到了 TextBox
中的第一行(Red")但是当我按下 Button2
时,我仍然得到红色".
When I press Button1
I get the first line in the TextBox
("Red") however when I press Button2
I still get "Red".
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
推荐答案
我建议使用 File.ReadAllLines
将行文本文件读入表单中的 String
数组Load
事件.然后您的 Button.Click
事件可以将所需的行复制到 TextBox
中.
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
在您的问题中,不清楚您是只想将所选行存储在 TextBox
中,还是将该行附加到 TextBox
.如果要追加,可以使用 TextBox1.Text &= lines(0) 'or lines(1)
(使用 &=
而不是 =
) 虽然在这种情况下,您可能还想添加某种分隔符.
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.
这篇关于将文本文件写入数组并读取特定行 VB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!