索引超出范围

时间:2019-03-23 10:30:11

标签: vb.net

我的代码不起作用,请帮助

Pose

1 个答案:

答案 0 :(得分:0)

我已更改为File类来完成您的任务。您无需声明File的实例。 StreamReader不需要关闭而是丢弃。 Using...End Using块或Try...Finally...End Try可以确保StreamReader的关闭和处置,因此File类更易于使用。

您不需要为strValues声明大小,因为它是在声明时初始化的。我添加了两个数组大小相同的检查。

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
    Dim lblControls() As Label = {lblName, lblID, lblGender, lblBirthDate, lblCity, lblContactNumber, lblAddress, lblHistory}
    Dim path As String = pathStorage & "Patients\" & selectedPatient & "\patientInfo.txt"
    Dim strValues = File.ReadAllLines(path) 'Returns a string array
    If lblControls.Length <> strValues.Length Then
        MessageBox.Show("Labels do not equal data.")
        Return
    End If
    Dim counter As Integer = 0
    For Each lbl As Label In lblControls
        lbl.Text = strValues(counter)
        counter += 1
    Next
End Sub