Steve's a D
Steve's a D

Reputation: 3821

formatting strings with StringBuilder.AppendFormat isn't working as expected

I'm trying to create a table with data using StringBuilders AppendFormat method. I want the text in the second and third column to be left aligned.

Here is an example I found on google: http://www.csharp-examples.net/align-string-with-spaces/

However, using the same code as the website I get different results. The placement of the second column text depends on the length of the first column text. Am I doing this wrong? Is there a better method that would be more suited for this task? I want a certain amount of space from the first character of the first column to the first character of the second column ( like the setw() method in c++)

symbolTableToString.AppendFormat(" {0,-20}  {1,-10}  {2,-10} {3,-10}",dataNode.token, dataNode.tokenClass, dataNode.tokenMode, dataNode.alias).AppendLine();

I'm putting each line into a text box and am unable to use a different widget as this is part of a homework assignment. enter image description here

Upvotes: 3

Views: 2635

Answers (2)

Your textbox has a variable width font, so using counts of spaces to align columns will almost never turn out well. Change the Font property of the textbox to a fixed width font such as Courier New.

Upvotes: 3

Wormbo
Wormbo

Reputation: 4992

Your problem isn't the AppendFormat, that actually seems to work correctly. Set that text box to use a monospaced font, e.g. Courier New or Consolas.

Upvotes: 0

Related Questions