Bali C
Bali C

Reputation: 31231

C# MessageBox For All Items In Array

I am trying to iterate through an array of strings and present all of them in a single messagebox. The code I have at the minute is this:

string[] array = {"item1", "item2", "item3"};
foreach(item in array)
{
   MessageBox.Show(item);
}

This obviously brings up a messagebox for each item, is there any way I can show them all at once in a messagebox outside the loop? I will be using \n to separate the items if this is possible, thanks.

Upvotes: 4

Views: 35684

Answers (5)

Zelig Herskovits
Zelig Herskovits

Reputation: 11

Put the message box out of the loop like this

string[] array = {"item1", "item2", "item3"};

string message5 = "";

foreach (string item in array)
{
    message5 += (item + "\n") ;
  
}
MessageBox.Show(message5);

Upvotes: 1

Independent
Independent

Reputation: 2987

I would see two common ways to do this.

        // Short and right on target
        string[] array = {"item1", "item2", "item3"};
        string output = string.Join("\n", array);
        MessageBox.Show(output);


        // For more extensibility.. 
        string output = string.Empty;
        string[] array = { "item1", "item2", "item3" };
        foreach (var item in array) {
            output += item + "\n"; 
        }

        MessageBox.Show(output);

Upvotes: 3

kawafan
kawafan

Reputation: 231

try Using this..

using System.Threading;



string[] array = {"item1", "item2", "item3"};


        foreach (var item in array)
        {

            new Thread(() =>
            {
                MessageBox.Show(item);
            }).Start();


        }

Upvotes: 0

Oskar Kjellin
Oskar Kjellin

Reputation: 21890

You can just use string.Join to make them into one string. Don't, use \n, it's better to use Environment.NewLine

string msg = string.Join(Environment.NewLine, array);

Upvotes: 5

Ani
Ani

Reputation: 113432

You can combine the individual strings from the array into a single string (such as with the string.Join method) and then display the concatenated string:

string toDisplay = string.Join(Environment.NewLine, array); 
MessageBox.Show(toDisplay);

Upvotes: 12

Related Questions