VB.NET 逐行读取文本文件并通过单击按钮设置文本框中的每一行 [英] VB.NET Read text file line by line and set every line in textbox with button clicks

查看:68
本文介绍了VB.NET 逐行读取文本文件并通过单击按钮设置文本框中的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我想逐行读取文本文件并在文本框中设置每个留置权时间我单击按钮这是我的代码并且工作正常.但我正在寻找一种简单的方法来阅读超过 5 行的大文本?

hello i want to read text file line by line and set every lien in textbox eash time i click the button this is my code and working fine. but i looking for easy way to read large text that has more thean 5 lines ?

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Static count As Integer
    count = count + 1

    Dim textfile As String = "c:\test.txt"
    If IO.File.Exists(textfile) Then
        Dim readLines() As String = IO.File.ReadAllLines(myFile)
        If count = 1 Then
            TextBox1.Text = readLines(0)
        End If
        If count = 2 Then
            TextBox1.Text = readLines(1)
        End If
        If count = 3 Then
            TextBox1.Text = readLines(2)
        End If
        If count = 4 Then
            TextBox1.Text = readLines(3)
        End If
        If count = 5 Then
            TextBox1.Text = readLines(4)
        End If
        If count = 6 Then
            TextBox1.Text = readLines(5)
        End If
    End If
End Sub

推荐答案

我认为您只需要在加载表单时读取一次文件(假设这里是 WinForms 示例)

I think you need to read the file just one time when you load your form (assuming a WinForms example here)

' Declare these two globally 
Dim readLines() As String
Dim count As Integer = 0

Private void Form_Load(sender As Oject, e As EventArgs) Handles Base.Load

    ' In form load, read the file, just one time
    Dim textfile As String = "c:\test.txt"
    If IO.File.Exists(textfile) Then
        readLines() As String = IO.File.ReadAllLines(myFile)
    else 
        TextBox1.Text "File not found"
    End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    ' Check if you have a file and if you don't have reached the last line
    if readLines IsNot Nothing AndAlso count < readLines.Length Then
        TextBox1.Text = readLines(count)
        count += 1
    else 
        TextBox1.Text "End of file"
    End If
End Sub

这篇关于VB.NET 逐行读取文本文件并通过单击按钮设置文本框中的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆