简体   繁体   English

从文本文件填充 vb.net 中的多个文本字段

[英]Populating multiple text fields in vb.net from a text file

I am attempting to populate 5 boxes on a form from a text file using VB.net. The text file is a report sent to me that contains an unknown number of lines as the events of each day are different.我正在尝试使用 VB.net 从文本文件填充表单上的 5 个框。文本文件是发送给我的报告,其中包含未知行数,因为每天的事件都不同。 In the text file, each line contains 5 items separated by a "~".在文本文件中,每行包含 5 个由“~”分隔的项目。

ie: AccountNumber~Name~Phone~email~data即:账号~姓名~电话~邮箱~数据

The form I have setup is just a simple form with 5 text boxes and 2 buttons.我设置的表单只是一个带有 5 个文本框和 2 个按钮的简单表单。 (In addition to the file menu to open the txt file). (除了文件菜单打开txt文件)。

The 2 buttons are for a "Previous record" and "Next Record" feature. 2 个按钮用于“上一个记录”和“下一个记录”功能。 They would do the obvious.他们会做显而易见的事情。

Here is the code I have so far.这是我到目前为止的代码。 It's all in the File > Open menu item (which may in itself be wrong) so I'm including that whole setup.这一切都在“文件”>“打开”菜单项中(这本身可能是错误的),所以我包括了整个设置。

I have it to where it will pop a message box for each item in each line one at a time.我有它,它将一次为每行中的每个项目弹出一个消息框。 Also, it keeps track by counting from 0 to 4 so I know when it's back at the first item.此外,它通过从 0 计数到 4 进行跟踪,所以我知道它何时回到第一项。 In testing, that works.在测试中,这有效。

I need to figure out how to get all 5 items from the first line to show in the text boxes and then, make the "Next" and "Previous" buttons go to the next or previous line and populate the text boxes from those.我需要弄清楚如何让第一行中的所有 5 个项目显示在文本框中,然后将“下一个”和“上一个”按钮 go 制作到下一行或上一行并从中填充文本框。 Each process I've tried has failed miserably.我尝试过的每个过程都惨遭失败。

Any assistance would be much appreciated.任何帮助将不胜感激。

Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
    Dim ofd As OpenFileDialog = New OpenFileDialog
    ofd.DefaultExt = "txt"
    ofd.FileName = "defaultname"
    ofd.InitialDirectory = "C:\users\%username%\desktop\"
    ofd.Filter = "Text files|*.txt"
    ofd.Title = "Select file"

    If ofd.ShowDialog() <> DialogResult.Cancel Then
        Using myreader As New Microsoft.VisualBasic.FileIO.TextFieldParser(ofd.FileName)
            myreader.TextFieldType = FileIO.FieldType.Delimited
            myreader.SetDelimiters("~")

            Dim currentrow As String()
            While Not myreader.EndOfData
                Try
                    currentrow = myreader.ReadFields()
                    Dim currentfield As String
                    For Each currentfield In currentrow
                        Dim count As Integer

                        If count = 4 Then
                            count = 0

                        Else
                            ' populate form

                            MsgBox(currentfield & " - " & count)
                            count = count + 1


                        End If

                    Next
                Catch ex As Microsoft.VisualBasic.
                    fileio.MalformedLineException
                    MsgBox("line " & ex.Message &
            "is not valid and will be skipped.")
                End Try
            End While

        End Using

    End If

End Sub

You need to store all the string arrays for each line in a structure OUTSIDE of the import method so that you can move forward and/or backwards through them.您需要将每一行的所有字符串 arrays 存储在导入方法外部的结构中,以便您可以向前和/或向后移动它们。

Here I've stored them in a List(Of String()) :在这里,我将它们存储在List(Of String())

Public Class Form1

    Private _dataIndex As Integer = -1
    Public Property DataIndex As Integer
        Get
            Return _dataIndex
        End Get
        Set(value As Integer)
            If value >= 0 AndAlso value < data.Count Then
                _dataIndex = value
                UpdateCurrentRecord()
            End If
        End Set
    End Property

    Private TextBoxes() As TextBox
    Private data As New List(Of String())

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' ...change the names of the textboxes below...
        TextBoxes = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5}
    End Sub

    Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
        Dim ofd As OpenFileDialog = New OpenFileDialog
        ofd.DefaultExt = "txt"
        ofd.FileName = "defaultname"
        ofd.InitialDirectory = "C:\users\%username%\desktop\"
        ofd.Filter = "Text files|*.txt"
        ofd.Title = "Select file"

        If ofd.ShowDialog() = DialogResult.OK Then
            _dataIndex = -1
            data.Clear()
            UpdateCurrentRecord()

            Using myreader As New Microsoft.VisualBasic.FileIO.TextFieldParser(ofd.FileName)
                myreader.TextFieldType = FileIO.FieldType.Delimited
                myreader.SetDelimiters("~")

                Dim currentrow As String()
                While Not myreader.EndOfData
                    Try
                        currentrow = myreader.ReadFields()
                        If currentrow.Length = 5 Then
                            data.Add(currentrow)
                        End If
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MessageBox.Show("Line " & ex.Message & " is not valid and will be skipped.")
                    End Try
                End While

                If data.Count > 0 Then
                    DataIndex = 0
                End If
            End Using
        End If
    End Sub

    Private Sub UpdateCurrentRecord()
        If _dataIndex >= 0 AndAlso _dataIndex < data.Count Then
            Dim row() As String = data(_dataIndex)
            If row.Length = 5 Then
                For i As Integer = 0 To 4
                    TextBoxes(i).Text = row(i)
                Next
            End If
        Else
            For Each tb As TextBox In TextBoxes
                tb.Clear()
            Next
        End If
    End Sub

    Private Sub btnPrev_Click(sender As Object, e As EventArgs) Handles btnPrev.Click
        DataIndex = (DataIndex - 1)
    End Sub

    Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
        DataIndex = (DataIndex + 1)
    End Sub

End Class

Insert this instead in your code to get the correct fields !将其插入您的代码中以获得正确的字段! !

If ofd.ShowDialog() <> DialogResult.Cancel Then
        Using myreader As New Microsoft.VisualBasic.FileIO.TextFieldParser(ofd.FileName)
            myreader.TextFieldType = FileIO.FieldType.Delimited
            myreader.SetDelimiters("~")
            Dim x As Short
            Dim currentrow As String()
            While Not myreader.EndOfData
                Try
                    currentrow = myreader.ReadFields()
                    Dim Count As Short = 0
                    For x = 0 To currentrow.Count - 1
                        Count = Count + 1

                        MsgBox(currentrow(x) & " - " & Count)

                       
                    Next
                Catch ex As Microsoft.VisualBasic.
                FileIO.MalformedLineException
                    MsgBox("line " & ex.Message &
        "is not valid and will be skipped.")
                End Try
            End While

        End Using
End If

You can also do this:-您也可以这样做:-

You can also use the logic I have shown above but first get all lines into a array - then manipulate each line:-您还可以使用我上面显示的逻辑,但首先将所有行放入一个数组中 - 然后操作每一行:-

Dim Lines = File.ReadAllLines(ofd.FileName)
        Dim Lp As Single
        Dim X As Short
        For Lp = 0 To Lines.Length - 1
            Dim items() As String = Split(Lines(Lp), "~")
            Dim Count As Short = 0
            For x = 0 To items.Count - 1
                Count = Count + 1
                MsgBox(items(X) & " - " & Count)
            Next
        Next

The following code works for me.以下代码对我有用。

Private curIndex As Integer = -1
Private maxIndex As Integer = 0
Private dic As Dictionary(Of Integer, String()) = New Dictionary(Of Integer, String())
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim lines = File.ReadAllLines(filePath).Where(Function(x) Not String.IsNullOrWhiteSpace(x))
    maxIndex = lines.Count - 1
    For i As Integer = 0 To maxIndex
        dic.Add(i, lines(i).Split("~"c).Where(Function(x) Not String.IsNullOrWhiteSpace(x)).ToArray())
    Next
    Label1.Text = "0"
    curIndex = 0
    TextBox1.Text = dic(0)(curIndex)
    TextBox2.Text = dic(0)(curIndex + 1)
    TextBox3.Text = dic(0)(curIndex + 2)
    TextBox4.Text = dic(0)(curIndex + 3)
    TextBox5.Text = dic(0)(curIndex + 4)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If Not curIndex - 1 < 0 Then
        curIndex -= 1
        Label1.Text = curIndex.ToString
        TextBox1.Text = dic(curIndex)(0)
        TextBox2.Text = dic(curIndex)(1)
        TextBox3.Text = dic(curIndex)(2)
        TextBox4.Text = dic(curIndex)(3)
        TextBox5.Text = dic(curIndex)(4)
    End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If Not curIndex + 1 > maxIndex Then
        curIndex += 1
        Label1.Text = curIndex.ToString
        TextBox1.Text = dic(curIndex)(0)
        TextBox2.Text = dic(curIndex)(1)
        TextBox3.Text = dic(curIndex)(2)
        TextBox4.Text = dic(curIndex)(3)
        TextBox5.Text = dic(curIndex)(4)
    End If
End Sub

You can use Dictionary to save line number and values.您可以使用字典来保存行号和值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM