将多个字符串格式化为一个,同时保持布局

时间:2013-11-27 14:02:26

标签: c# winforms listbox string-formatting

我有一个列表框,我填充数据;一串可变长度和3个整数,格式为固定长度。

我无法弄清楚如何让字符串文本只占用x个字符

30个字符的空间,如果字符串长度为5个字符,则添加25个字符的填充。如果字符串长度为10个字符,则添加20个字符的填充。

我的最新尝试看起来像:

int padding = 30 - item.ProductName.Length;
string prodName = String.Format("{0, " + padding + "}",item.ProductName);
string quant = String.Format("{0,15}", item.GetQuantity);
string price = String.Format("{0,30:C2}", item.LatestPrice);
string total = String.Format("{0,30:C2}", item.TotalOrder);
string temp = prodName + quant + price + total;
return temp;

但那仍然不起作用:http://i.imgur.com/RfxFCO3.png

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题。

//int padding = 30 - item.ProductName.Length;
string prodName = String.Format("{0, -30}", item.ProductName);
string quant = String.Format("{0,15}", item.GetQuantity);
string price = String.Format("{0,30:C2}", item.LatestPrice);
string total = String.Format("{0,30:C2}", item.TotalOrder);
string temp = prodName + quant + price + total;
return temp;

如果您希望产品名称绝对限制为30个字符,那么您需要截断产品名称> 30个字符。

string prodName = String.Format("{0, -30}", item.ProductName.Length > 30 ? item.ProductName.Substring(0,30): item.ProductName);