Backslash
Backslash

Reputation: 109

Xml node foreach loop

I'm currently trying to read a xml file and add a control for every "Mods" entry.

<Modlist>
  <Mods>
    <Mod>Test1</Mod>
    <Version>1.0</Version>
  </Mods>
  <Mods>
    <Mod>Test2</Mod>
    <Version>2.0</Version>
  </Mods>
  <Mods>
    <Mod>Test3</Mod>
    <Version>3.0</Version>
  </Mods>
</Modlist>

Basically i want to add a control to a panel for every listed mod in the xml.

XDocument Mods = XDocument.Load(@"C:\dataset.xml");

foreach (var mod in Mods.Descendants("Mods"))
{
    Button modbutton = new Button();

    modbutton.Text = mod.Element("Mod").Value;

    panel1.Controls.Add(modbutton);
}

Its working, but its only creating one button and seems to stop. In my example it should create 3 buttons. What do i have to change? Whats wrong with my code?

Upvotes: 0

Views: 207

Answers (2)

King
King

Reputation: 179

ur code working perfectly, but the problem is buttons are placed in same place. u need change the position.

Try this

       XDocument Mods = XDocument.Load(@"C:\dataset.xml");

            int I = 10;
            foreach (var mod in Mods.Descendants("Mods"))
            {
                Button modbutton = new Button() { Top = 10 + I, Left = 10  };


                modbutton.Text = mod.Element("Mod").Value;

                panel1.Controls.Add(modbutton);

                I += 50;
            }

Upvotes: 1

tezzo
tezzo

Reputation: 11105

Your code to read xml is correct but you are putting each button one over the other. Set .Location property for every Button.

Upvotes: 1

Related Questions