I am new to c# and in this case, I want to align text columns in a text block. So basically I am trying to print a receipt and on the receipt, it should look like this.
For example:
1 Dinner Set $15.00
1 Hamburger Combo $10.00
Basically, I want to align my text column for the receipt. Since the food item name length varies from the different food item. For instance "Dinner Set" and "Hamburger Combo" have different lengths. Therefore, whenever I use the code below it would come up like this
1 Diner Set $15.00
1 Hamburger Combo $10.00
Here is the code:
foreach (OrderItem ot in orderItemList)
{
x += $"\n{ot.Quantity} {ot.Item.Name}\t\t
${ot.GetItemTotalAmnt().ToString("0.00")}\n";
}
Since I don't hardcode each line is there a way to set a fixed width on {ot.Item.Name}?
As long as you're using a fixed-width font, use something like this:
string.Format("{0,-20}", ot.Item.Name)
The value after the comma says to use that many character spaces in the resulting string. If you use the following (notice I removed the minus sign):
string.Format("{0,20}", ot.Item.Name)
Then the text will be right-aligned within those spaces.
You can specify the field width and format specifiers the same way with string interpolation as you can with String.Format()
.
x += $"\n{ot.Quantity} {ot.Item.Name,-20} ${ot.GetItemTotalAmnt():C}\n";
And if you don't want to hardcode 20, just use the maximum Item.Name
as the field width.
var maxLength = orderItemList.Max(ot => ot.Item.Name.Length)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With