从逗号分隔的文本文件中读取值并添加,创建类的对象,然后将对象添加到集合中

时间:2017-09-21 23:31:08

标签: vb.net list object text-files streamreader

我目前有以下代码:

Public Class CPUForm

    Dim myCPUList As New List(Of CPUClass)
    Dim Counter As Integer = 0

    Private Sub CPUForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        OpenFileDialog.ShowDialog()

        Try
            If IO.File.Exists(OpenFileDialog.FileName) = False Then
            End If
        Catch ex As IO.FileNotFoundException
            MessageBox.Show("The File Could Not Be Found", "Alert")
        End Try
        If IO.File.Exists(OpenFileDialog.FileName) = True Then
            Dim sr As IO.StreamReader = IO.File.OpenText(OpenFileDialog.FileName)
            Dim line As Object
            Dim data() As Object
            Do Until sr.EndOfStream
                line = sr.ReadLine
                data = line.Split(",")
                Dim ACpu As New CPUClass(data(0), data(1), data(2), data(3), data(4), data(5))
                myCPUList(Counter) = ACpu
                Counter += 1
            Loop
            sr.Close()
        End If
        lstOut.DataSource = Nothing
        lstOut.DataSource = myCPUList
    End Sub
End Class

此处的目标是从逗号分隔的文本文件中读取值,创建类的对象,将这些对象添加到集合中,然后使用重写的ToString方法在列表框中显示集合。

现在即使在运行时也没有错误。问题是选择了一个文件,没有任何反应。列表框中没有显示任何内容,就好像没有任何内容添加到集合中一样。此外,存在重载的构造函数以接收正在读入的值。

1 个答案:

答案 0 :(得分:0)

原来代码很好,问题是文本文件中不合适的逗号。