简体   繁体   中英

Add multiple lines in a textblock without over writing the previous line

I'm trying to output an array into a textblock with each element in a line using a for loop but it only outputs the final element.

I think it's over writing the current output with the next one. Is there a way I can print the entire array with each element on a new line using a single textblock? This is what I'm trying currently.

string nl = Environment.NewLine;

for (int i = 0; i < 10; i++)
        {
            display_all_output2.Text = (arrayid[i] + nl);
        }
        

There's a few ways to go about this the simplest is just to add the text onto the existing text.

display_all_output2.Text += (arrayid[i] + nl);

This is not best practice here though for two reasons, string are an immutable type, and actually have to have a new one be built in the background every time you do this, and this is in a loop so it's happening multiple times. You might not notice the speed difference on 10 loops, but there's aa few straightforward ways of dealing with appending text.

First there's the string.Join a few people mentioned.

string.Join(Environment.NewLine, arrayid);

That does it in one line instead of multiple. The other way, if you do need to loop through the array for some other reason, is with a StringBuilder.

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 10; i++)
    {
        sb.Append(arrayid[i] + Environment.NewLine));
    }

StringBuilder are made to quickly be expanded and have the contents modified.

Edited to add: When done building the string with StringBuilder, you will usually retrieve the contents of the StringBuilder with.ToString()

display_all_output2.Text = sb.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM