我正在做一个ITP项目。我需要将列表框中的所有项目添加到文本框中。我尝试使用的代码是:
tbxReceipt.Text = "The items you purchased are:\r\n\r\n" + lbxItemBought.Items.ToString()
+ "\r\n\r\nYour total price was:" + lblLastCheckout.Text;
但是当我使用代码lbxItemBought.Item.ToString()时,它会出现错误:
System.Windows.Forms.ListBox + ObjectCollection。
我想知道是否有另一种方法可以做到这一点?
感谢
答案 0 :(得分:1)
首先,如果您使用循环进行字符串操作,请使用StringBuilder
现在尝试
StringBuilder a = new StringBuilder();
a.Append("The items you purchased are:\r\n\r\n");
foreach (var item in lbxItemBought.Items)
{
a.Append(item.ToString());
}
a.Append("\r\nYour total price was:");
a.Append(lblLastCheckout.Text);
tbxReceipt.Text = a.ToString();
答案 1 :(得分:1)
您需要遍历列表框。
string value = "The items you purchased are:\r\n\r\n";
foreach (var item in lbxItemBought.Items)
{
value += "," + item.ToString();
}
value += "\r\n\r\nYour total price was:" + lblLastCheckout.Text ;
tbxReceipt.Text = value;
答案 2 :(得分:0)
该消息没有错误,它只是列表框的Items
- 属性的字符串表示形式。
如果要获取项目名称的连接(例如),则必须遍历Items
- 集合,将单个元素强制转换为放入其中的内容,然后连接显示字符串。例如,如果您的商品类型为SomeItem
并且它具有Name
等属性,则可以像这样使用LINQ:
var itemNames = string.Join(", ", lbxItemBought.Items
.Cast<SomeItem>()
.Select(item => item.Name));
tbxReceipt.Text = "The items you purchased are:\r\n\r\n" + itemNames + "\r\n\r\nYour total price was:" + lblLastCheckout.Text;
答案 3 :(得分:0)
string result = string.Empty;
foreach(var item in lbxItemBought.Items)
result + = item.ToString()+Environment.NewLine;
txtReceipt.Text = result;