syncis
syncis

Reputation: 1433

string formatting

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.

Upvotes: 2

Views: 565

Answers (3)

Till
Till

Reputation: 3154

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.

Upvotes: 3

pdresselhaus
pdresselhaus

Reputation: 699

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.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292465

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

Upvotes: 3

Related Questions