如何使用StreamReader和数组填充TextBoxes?

时间:2017-06-07 00:53:00

标签: arrays vb.net textbox streamreader

我正在尝试创建一个解决方案,从文本文件中提取员工信息,将其加载到数组中,然后在单击按钮时从数组中填充一系列TextBox。

我已经取得了一些进展,我从数组中提取数据,并将其放入文本框中。但是,它只是填充TextBoxes的单个字母,而不是完整数据。

我已经附上了我一直致力于实现目标的代码,但我真的在接下来要去哪里。

作为参考,文本文件中的数据是:

  

贾尼丝
  琼斯
  101个
  5.25
  克里斯
  O Connel
  102个
  5.35
  卡伦
  菲斯克
  103个
  6.00
  汤姆
  温
  104个
  5.75

Private Sub nextButton_Click(sender As Object, e As EventArgs) Handles nextButton.Click
    Dim EmpoyeeStreamReader As New StreamReader("employee.txt")
    Dim EmployeeLineInfoString As String
    Dim EmployeeIndex As Decimal

    EmployeeLineInfoString = EmpoyeeStreamReader.ReadLine()

    Dim EmployeeArray = (EmployeeLineInfoString).ToString

    EmployeeIndex = 0

    Try
        For EmployeeIndex = 0 To 16
            firstNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            lastNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            employeeNumberTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            payRateTextBox.Text = EmployeeArray(EmployeeIndex)
        Next

        For EmployeeIndex = 5 To 16
            firstNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            lastNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            employeeNumberTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            payRateTextBox.Text = EmployeeArray(EmployeeIndex)
        Next
    Catch ex As Exception
        MessageBox.Show("All Employee's have been entered")
    End Try

1 个答案:

答案 0 :(得分:0)

尝试这样的事情(尽管在Form级别声明StreamReader可能更好!):

Private Sub nextButton_Click(sender As Object, e As EventArgs) Handles nextButton.Click
    Static EmpoyeeStreamReader As StreamReader = Nothing

    If IsNothing(EmpoyeeStreamReader) Then
        EmpoyeeStreamReader = New StreamReader("employee.txt")
    End If

    If Not EmpoyeeStreamReader.EndOfStream Then
        Try
            firstNameTextBox.Text = EmpoyeeStreamReader.ReadLine
            lastNameTextBox.Text = EmpoyeeStreamReader.ReadLine
            employeeNumberTextBox.Text = EmpoyeeStreamReader.ReadLine
            payRateTextBox.Text = EmpoyeeStreamReader.ReadLine
        Catch ex As Exception
            MessageBox.Show("Error Reading Record: Insufficient Number of Lines!")
        End Try
    Else
        MessageBox.Show("No more records!")
        EmpoyeeStreamReader.Close()
        EmpoyeeStreamReader = Nothing
    End If
End Sub