whats wrong with this foreach statement?

Last post 05-08-2008 2:24 PM by AceCorban. 3 replies.

Sort Posts:

  • whats wrong with this foreach statement?

    05-08-2008, 2:05 PM
    • Loading...
    • sul125
    • Joined on 04-18-2008, 7:49 AM
    • Posts 21

    i created this simple app.

    protected void Button1_Click(object sender, EventArgs e)

    {

    XmlDocument doc = new XmlDocument();

    doc.Load(this.TextBox1.Text);

    XmlElement root = doc.DocumentElement;

     

    foreach (XmlNode node in root.FirstChild.ChildNodes)

     

    {

    if (node.Name == "item")

    {

    string title = null;string link = null;

     

    foreach (XmlNode itemNode in node.ChildNodes)

    {

    if (itemNode.Name == "title")

    {

    title = itemNode.InnerText;

    }

    if (itemNode.Name == "link")

    {

    link = itemNode.InnerText;

    }

    }

    Label2.Text =title;

     

    }

     

    }

    }

     

    when you put Label2.Text =title; it show only 1 title

    when you put Label2.Text +=title; it works fine what the magic of thisd + ?

  • Re: whats wrong with this foreach statement?

    05-08-2008, 2:22 PM
    Answer
    • Loading...
    • figz
    • Joined on 09-07-2007, 8:45 PM
    • Posts 85

    The += operator is the same as saying "Label2.Text = Label2.Text + title;"

    It adds the next title on every pass.  If you only use the = operator, your Label2.Text is completely cleared and reassigned every time.

    Hope this helps!

    -figz 

  • Re: whats wrong with this foreach statement?

    05-08-2008, 2:24 PM
    • Loading...
    • che3358
    • Joined on 09-25-2003, 10:23 AM
    • Cleveland, OH
    • Posts 700

    Label2.Text +=title  :  Label2.Text = Label2.Text  + title

  • Re: whats wrong with this foreach statement?

    05-08-2008, 2:24 PM
    • Loading...
    • AceCorban
    • Joined on 08-23-2007, 11:43 AM
    • Monterey, CA
    • Posts 374

    When you say "label.Text = whatever" in each iteration of the loop, you are overwriting the previous value of the label.

    When you say "label.Text += whatever" it is the same as saying "label.Text = label.Text + whatever".  this means it is concatenating "whatever" to the previous value of the label.

    I never lose, some people are just better than me at winning.
Page 1 of 1 (4 items)