Search code examples
c#messageboxstring.format

String.Format()'s alignment behaves different when it comes to MessageBox


I am using String.Format() to format some text information and it works perfectly with "Console.WriteLine()" as documented in msdn.

My code is like this:

        StringBuilder strBuilder = new StringBuilder();
        strBuilder.AppendLine("Summary Information:");
        strBuilder.AppendFormat("{0,-10}{1,-8}{2,-10}{3,-30}{4,-7}\n", "Header1", "Header2", "Header3", "Header4", "Header5");
        strBuilder.AppendFormat("{0,-10}{1,-8}{2,-10}{3,-30}{4,-7}\n\n", "A", "1", "Y", "Long Information", "13");
        string result = strBuilder.ToString();

        Console.WriteLine(result);

The console result is shown below.

Console Result

But, when I try to show it on a MessageBox, the columns are shifting. Somehow the spaces are swallowed.

 MessageBox.Show(result, "MBox Test");

MessageBox result

It is also okay, because I wasn't very kneen on the "MessageBox" class of the .Net. It has so much limitations.

So I decided to implement a custom form to display this message. I have tried with Label and RichTextBox. But unfortunately the result was exactly same as the MessageBox.

And I am confused. Why .Net's own controls can not support String.Format()'s alignment. Is there any way I can handle this situation?


Solution

  • The String.Format(...) works perfectly well, but it does not align as a table in your message box because of the font!

    In your console you use a fixed-width (monospace) font, but the messagebox uses one with dynamic width. Therefore e.g. an "M" consumes more space than an "i" or a " " (space) and this messes up your layout.

    As you can't change the messagebox font, you have to create your own frame with any kind of text widget that supports custom fonts, e.g a TextBox or just an ordinary Label.