1

I am reading an XML file and use the data for my TreeView in C#. My program returns an error

An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll.

Why?

XML file

<ListOfTopics>
  <MainTopic url="index.html" title="Homes">
    <SubTopic url="index.html" title="Sub Topic1"/>
    <SubTopic url="index.html" title="Sub Topic2"/>
    <SubTopic url="index.html" title="Sub Topic3"/>
  </MainTopic>
</ListOfTopics>

C# code

public void LoadTopics()    
{
    XmlDocument xml = new XmlDocument();
    xml.Load("topics.xml");
    int i = 0;

    foreach (XmlElement el in xml.DocumentElement.ChildNodes)
    {           
        TreeNode node = new TreeNode();
        node.ToolTipText = el.GetAttribute("url");
        node.Name = el.GetAttribute("title");
        node.Text = el.GetAttribute("title");
        topicTree.Nodes.Add(node);

        if (el.HasChildNodes)
        {
            foreach (XmlElement es in el.ChildNodes)
            {
                TreeNode nodes = new TreeNode();
                nodes.ToolTipText = es.GetAttribute("url");
                nodes.Name = es.GetAttribute("title");
                nodes.Text = es.GetAttribute("title");
                topicTree.Nodes[i].Nodes.Add(node);
            }

        }
        i++;   
    }
}

1 Answer 1

1

I ran your code and didn't have an exception, however I did find a bug in your code:

topicTree.Nodes[i].Nodes.Add(node);

You are re-adding the parent node, change it to:

topicTree.Nodes[i].Nodes.Add(nodes);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.