3

I was doing an ITP project. I needed to add all the items in the listbox to a textbox. The code that i tried using was:

tbxReceipt.Text = "The items you purchased are:\r\n\r\n" + lbxItemBought.Items.ToString()
+ "\r\n\r\nYour total price was:" + lblLastCheckout.Text;

But when i use the code lbxItemBought.Item.ToString(), it comes up with the error:

System.Windows.Forms.ListBox+ObjectCollection.

I was wondering if there was another way to do it?

thanks

4

4 回答 4

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; 
于 2013-11-05T08:40:51.563 回答
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();
于 2013-11-05T08:38:11.833 回答
0

该消息没有错误,它只是Items列表框的 -property 的字符串表示形式。

当您想要获得项目名称的串联时(例如),您必须遍历Items-collection,将单个元素转换为您放入其中的内容,然后串联显示字符串。例如,如果您的项目的类型是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;
于 2013-11-05T08:38:13.073 回答
0
string result = string.Empty;

foreach(var item in lbxItemBought.Items)
    result + = item.ToString()+Environment.NewLine;

txtReceipt.Text = result;
于 2013-11-05T08:39:04.547 回答