1

I want fixed spacing between words in a string similar to what you have in a datagrid.

I tried:

string item = String.Format("{0,-9}{1,-42}{2,-24}{3,0}", ++i, itemName, itemQuantity, totalItemPrice.ToString("#,##0.00") + System.Environment.NewLine);

But since the itemName length is varaible itemQuantity and totalItemPrice do not maintain their positions and get pushed forward.

The string is subsequently assigned to a RichTextBox.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
kr13
  • 527
  • 4
  • 8
  • 22

2 Answers2

3

You can use string.Format() to line things up if you are using a monospaced (fixed-pitch) font.

However, you will not be able to line things up with a proportional font using string.Format() unless you are only displaying digits (which all have the same width even in a proportional font).

Since you are using RTF, you may be able to use a table if you need to use a proportional font.

See here for some more information: Using Tables in RTF

But the easiest solution is just to use a monospaced font, if you can.

Community
  • 1
  • 1
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

You can do like this:

I have just modified the way you have used the values and I can get the data displayed as data grid.

 string itemName = "phone";

 int itemQuantity = 5, totalItemPrice=50;

 string item = String.Format("{0,-2}{1,-10}{2,-5}{3,-5}", ++i, itemName, itemQuantity, totalItemPrice.ToString("#,##0.00")+System.Environment.NewLine);
Jigna
  • 75
  • 1
  • 11