This has probably a simple solution, but i cannot find any obvious wrong.

This is a simple button event and the supposed output in Label5 should be: One Two Three.
Now, I can only get "Three", the last value in the array.

protected void Button4_Click(object sender, EventArgs e)
        {

            string[] stringArray = { "One", "Two", "Three" };

            foreach (string element in stringArray)
            {
                Label5.Text = (element + " ");
            }

            
        }

Recommended Answers

All 5 Replies

Why, take a second look at that code! You're overwriting the value each time through the loop?

You want Label5.Text += element + " "; inside the loop, but don't forget to overwrite it with an empty string before. Of course, that's a mere incremental improvement. You probably really want Label5.Text = string.Join(" ", stringArray);

It's wrong. you assigned the string element every time to Label5.
This is correct:

protected void Button4_Click(object sender, EventArgs e)
        {

            string[] stringArray = { "One", "Two", "Three" };

            foreach (string element in stringArray)
            {
//you need to ADD with "+" every time the string to the label text
                Label5.Text += (element + " ");
            }

            
        }

No, that's wrong too because your code will append to whatever was previously stored in Label5.Text :P

LOL YOU ARE FUNNY !
did he mention that Label5 has Text property set to "" or something else? i thing anyone can figur this out. So don't feel to SMART:twisted:

Thank you guys !

This was what I was looking for, it replaces the current string from the label and print the values I want from the array: "One Two Three" in a row.

Label5.Text = string.Join(" ", stringArray);


best regards
TobbeK

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.