Search code examples
c#arraysmultidimensional-arraymessagebox

Displaying the values of a multidimensional array in a MessageBox


I am just now learning about multi-dimensional arrays and message boxes. I am currently have a issue in creating 2 columns in my message box. I can currently get it to print up the random numbers I need, but only in one column. Thanks for the help!

string  msg = "";

Random numb = new Random();
int[,] thing = new int[ 10, 2 ];

thing[0, 0] = numb.Next(0,10);
thing[0, 1] = numb.Next(0,10);
thing[1, 0] = numb.Next(0,10);
thing[1, 1] = numb.Next(0,10);
thing[2, 0] = numb.Next(0,10);
thing[2, 1] = numb.Next(0,10);
thing[3, 0] = numb.Next(0,10);
thing[3, 1] = numb.Next(0,10);
thing[4, 0] = numb.Next(0,10);
thing[4, 1] = numb.Next(0,10);

thing[5, 0] = numb.Next(0,10);
thing[5, 1] = numb.Next(0,10);
thing[6, 0] = numb.Next(0,10);
thing[6, 1] = numb.Next(0,10);
thing[7, 0] = numb.Next(0,10);
thing[7, 1] = numb.Next(0,10);
thing[8, 0] = numb.Next(0,10);
thing[8, 1] = numb.Next(0,10);
thing[9, 0] = numb.Next(0,10);
thing[9, 1] = numb.Next(0,10);

foreach (int x in thing) 
msg = msg + x + "\n";
MessageBox.Show(msg, "Table");

Solution

  • Change this:

    foreach (int x in thing) 
    msg = msg + x + "\n";
    MessageBox.Show(msg, "Table");
    

    To :

    for (int i = 0; i < thing.GetLength(0); i++)
        msg += String.Format("{0}   {1}\n", thing[i, 0], thing[i, 1]);
        //msg += thing[i, 0] +  "  " +  thing[i, 1] + "\n";
    
    MessageBox.Show(msg, "Table");
    

    Explanation:

    Method GetLength(0) returns length of dimension for our x (it's basically like array.Length for simple array but with specific dimension) and we use i variable and for loop to iterate through it. In y we have only 2 elements so we can just use [0] and [1] indexes as we know there are only two elements there. This explains the line:

    msg += thing[i, 0] +  "  " +  thing[i, 1] + "\n";
    

    Be careful with concatenating string like that, as if you don't add this space " " between your numbers compiler will just add them, so element like [33, 10] will be concatenated to string like : "43 \n" instead of "33 10 \n".

    P.S. So let's use String.Format method to make sure it's formatted well :

    msg += String.Format("{0} {1}\n", thing[i, 0], thing[i, 1]);