tags:

views:

21

answers:

2

I am trying to add get items from an xml document and load it into a listview. I keep getting an System.OutOfMemory exception on the line projects.Add(project). What am I doing wrong and how do I do it correctly? I got this code from murach's beginning visual basic.NET. When I run this it adds random spaces between the items in the listview

Structure ProjectInfo
    Dim name As String
    Dim fileextentions As ArrayList
    Dim imagepath As String
End Structure

Dim project As ProjectInfo
Dim projects As New ArrayList()

'The project is loading
Private Sub diaNewProject_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    'Set the default filepath
    txtFilepath.Text = "C:\Users\" & GetUserName() & "\Documents\Homerun IDE\Projects"

    'Load the project types
    If LoadProjects() Then
        For Each Me.project In projects
            'Add the items
            ltvItems.Items.Add(project.name)
        Next
    Else
        'Close the form
        Me.Close()
    End If

End Sub
Private Function LoadProjects() As Boolean

    Dim ProjectReader As New XmlTextReader(_globals.ProjectsListFilename)
    ProjectReader.WhitespaceHandling = WhitespaceHandling.None
    Try
        Do Until ProjectReader.Name = "projecttype"
            ProjectReader.Read()
        Loop
        Do While ProjectReader.Read()
            If ProjectReader.Name = "projecttype" Then
                project.name = ProjectReader.Item(Name)
                projects.Add(project)
            End If
        Loop
        ProjectReader.Close()
    Catch ex As XmlException
        _logger.LogException(ex, TraceEventType.Critical, "Load Projects Error", "Make sure that your projectstypes.xml file is correctly formatted. In your settings " & _
                             "you can reset the file to your its default.")
        Return False
    End Try

    Return True

End Function
+2  A: 

You have an infinite loop here:

Do While ProjectReader.Name = "projecttype"
        project.name = ProjectReader.Item("name")
        'TODO: extension
        'TODO: imagepath
        projects.Add(project)
Loop

You have to either advance the reader inside the loop or remove this loop.

EndangeredMassa
I have no way of knowing how many items are in the xml file so I don't see a way to advance the loop and how would I do this without the loop?
muckdog12
I don't know the details of the XML file, but you probably want to add `ProjectReader.Read()` at the bottom of this loop.
EndangeredMassa
A: 
    Do While ProjectReader.Read() 
      If ProjectReader.Name = "name" Then
        ...
      End If 
    Loop 

You should also note that project.name = ProjectReader.Item("name") will return the value of the attribute @name so for it to work the element structure would have to be something like.

<name name="project name"/>

Which probably isn't what you want. If you want the element value then use project.name = ProjectReader.ReadString()

fivebob