0

我必须编写一个从 csv 文件读取的大学 WPF 应用程序。当我想将 CSV 行的部分输出到数组中时,我得到一个空引用异常。您可以在评论中找到错误发生的行。这是代码。

Imports System.Windows.Forms
Imports System.IO
Imports System.Globalization

Class MainWindow
Private foldername As String
Private arrGemeenten As String()
Private arrOppervlakte As Double()
Private arrInwoners As Integer()
Private arrDeelgemeenten As Integer()


Private Sub cboProvincie_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cboProvincie.SelectionChanged
    CSVInlezen()
End Sub

Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded


    FileBrowserAanmaken()
    comboBoxVullen()

End Sub



Private Sub comboBoxVullen()
    For Each file As String In IO.Directory.GetFiles(foldername)

        If file.EndsWith(".csv") Then
            Dim filenaam As String = System.IO.Path.GetFileNameWithoutExtension(file)
            cboProvincie.Items.Add(filenaam)
        End If

    Next
End Sub

Private Sub FileBrowserAanmaken()
    'folderbrowserdialog aanmaken
    Dim fbd As New FolderBrowserDialog

    fbd.SelectedPath = AppDomain.CurrentDomain.BaseDirectory


    ' Show the FolderBrowserDialog. 

    Dim result As DialogResult = fbd.ShowDialog()

    If (result = Forms.DialogResult.OK) Then
        foldername = fbd.SelectedPath
    End If
End Sub



Private Sub CSVInlezen()
    Dim filepath As String = foldername & "\" & cboProvincie.SelectedValue & ".csv"
    If File.Exists(filepath) Then
        fileInlezenHulpMethode(filepath)
    End If
End Sub

Private Sub fileInlezenHulpMethode(ByVal path As String)
    'declarations
    Dim sr As New StreamReader(path)
    Dim iTeller As Integer = 0
    Dim arrLijn As String()
    Dim culture As New System.Globalization.CultureInfo("nl-BE")

    'eerste lijn meteen uitlezen, dit zijn kolomkoppen en hebben we niet nodig
    'read out first line, these are titles and we don't need them
    sr.ReadLine()

    Do While sr.Peek <> -1
        Dim lijn As String = sr.ReadLine()
        arrLijn = lijn.Split(";")
        arrGemeenten(iTeller) = Convert.ToString(arrLijn(0)) 'HERE I GET THE ERROR!
        arrOppervlakte(iTeller) = Double.Parse(arrLijn(2), NumberStyles.AllowDecimalPoint, culture.NumberFormat)
        arrInwoners(iTeller) = Integer.Parse(arrLijn(3), NumberStyles.Integer Or NumberStyles.AllowThousands, culture.NumberFormat)
        arrDeelgemeenten(iTeller) = Convert.ToString(arrLijn(4))
    Loop
End Sub

End Class
4

1 回答 1

1

你还没有创建数组,你只是为它创建了一个引用。要创建数组,您需要指定一个大小,例如:

Private arrGemeenten As String(100)

但是,要指定大小,您需要在创建数组时知道大小。(好吧,实际上您将所有数据都放在第一项中,所以只是大小1可以防止它崩溃,但我不认为那是您想要的。)您可能想要使用列表来代替:

Private gemeenten As New List(Of String)()

然后您使用该Add方法将项目添加到列表中:

gemeenten.Add(Convert.ToString(arrLijn(0)))

此外,考虑将数据放在自定义对象的单个列表中,而不是具有多个松散耦合数据列表。

于 2012-09-29T22:49:25.360 回答