Better c# code - newbie question

i have some c# code that pulls value from an XML file. The code works, but I am positive there is a better way to code this - i’m sure using a “while” statement.

note: linkDesc1, linkDesc2, linkDesc3 are asp:label controls.

protected void Page_Load(object sender, EventArgs e)
{
    string fileName = "C:/Links.xml";
    XPathDocument doc = new XPathDocument(fileName);
    XPathNavigator nav = doc.CreateNavigator();

    // Compile a standard XPath expression
    XPathExpression exprd;
    exprd = nav.Compile("/Links/Description");
    XPathNodeIterator iterator = nav.Select(exprd);


    try
    {
        iterator.MoveNext();

XPathNavigator nav1 = iterator.Current.Clone();
LinkDesc1.Text = nav1.Value;

        iterator.MoveNext();

XPathNavigator nav2 = iterator.Current.Clone();
LinkDesc2.Text = nav2.Value;

iterator.MoveNext();
XPathNavigator nav3 = iterator.Current.Clone();
LinkDesc3.Text = nav3.Value;

i guess i have two specific questions:
1)how do you setup a variable to refer to a series of control IDs, eg linkDescN for linkdesc1/2/3
2)I would think I wouldnt need a new string for nav1/nav2/nav3. isnt there a way to just replace nav1 with the next iterator value.

Thanks

Sure man…


while (iterator.MoveNext())
{
XPathNavigator nav1 = iterator.Current.Clone();
LinkDesc1.Text = nav1.Value;
}



But that will set every iteration to linkdesc1, won’t it. I want each iteration in a different label

This might help you:

http://social.msdn.microsoft.com/Forums/en/winforms/thread/da4d5435-0839-4eb6-861d-6afd5bc63442

Well, there are lots of ways to approach this, but it comes down to your page setup:

  1. Dynamically add Label controls to a container

while (iterator.MoveNext())
{
XPathNavigator nav1 = iterator.Current.Clone();
Label LinkDesc = new Label();
LinkDesc.Text = nav1.Value;

containerControl.Controls.Add(LinkDesc);
}

  1. Find the Label controls in a container

int ittr = 1;
while (iterator.MoveNext())
{
XPathNavigator nav1 = iterator.Current.Clone();
Label LinkDesc = (Label)container.FindControl("LinkDesc" + (ittr++));
LinkDesc.Text = nav1.Value;
}

And a few other other things I could think of. But the best would be to have a repeater or similar control and bind that to your XmlDocument.

Can you post the XML format? In most cases you don’t even want to touch the Xml directly. Boys parse, real men deserialize.

haha. Well said.

this is what I am using for XML, but i have no doubt it could be better.

<?xml version=“1.0”?>
<Links>
<Description>this is a story <br> it is really good</Description>
<Description>test desc</Description>
<Description>this is another test description</Description>
<Url>www.google.com</Url>
<Url>www.yahoo.com</Url>
<Url>test.com</Url>
</Links>

Yeah, I’d run with:


<links>
<link>
<description>yad yada yada</description>
<url>http://yada.example.com</url>
</link>
</links>

Then you should be able to use the XmlDeserializer to deserialize your links.