2

I am trying to align values. I wonder why this happen :

        string value = "";

        value += string.Format("{0,-10}", "value");
        value += string.Format("{0,5}", "value");

        value += Environment.NewLine;

        value += string.Format("{0,-8}", "val");
        value += string.Format("{0,7}", "value");

        MessageBox.Show(value);

If i check value before i do "MessageBox.Show() it is correct. The result is:

value     value
val       value

As they should be, but when i do MessageBox.show() then they get like this :

   value     value
   val     value

I really cant understand why it changes the string with show()? Same thing happens when i am trying to print "value", then it doesnt align correct.

Btw: this is just a test code so you could understand the problem that i am having with the real code.

syncis
  • 1,395
  • 4
  • 25
  • 43

3 Answers3

3

That's because the font used by MessageBox.Show doesn't have a fixed width...

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
3

This might be caused by the fact that the font used in the message box is not monospaced, meaning that each character takes an equal amount of horizontal space. The font you are using in the Visual Studio debugger probably is, which is why the padding looks entirely different.

You could try if using tabs instead of spaces for your formatting gives better results.

Till
  • 3,084
  • 17
  • 18
0

According to this answer the way to go is using \t as a column seperator.

This definitely involves checking the length of all the words of each single column. This way you would know whether to use a single \t or double \t\t etc.

Community
  • 1
  • 1
pdresselhaus
  • 679
  • 14
  • 32
  • @syncis Sorry, seems that I have paid too little attention. I thought your only task was to show the values via MessageBox.Show() which can be fulfilled using the method mentioned above. In your case you might want to try to create your own message box a mentioned [here](http://stackoverflow.com/questions/232066/messagebox-show-font-change/232077#232077). Then you could switch to a non-monospaced font which you could use for printing purposes as well. – pdresselhaus Jun 23 '11 at 20:27