简体   繁体   中英

how to add items from listbox to textbox c#

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

Firstly, if you are doing string manipulation with a loop, use a StringBuilder

Now try

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();

You need to iterate through listbox.

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; 

That message is no error, it is just the string representation of the Items -property of your listbox.

When you want to get a concatenation of the item names (for example), you must iterate over the Items -collection, cast the single elements to the things you put into it and then concatenate a display string. For example, if the type of your items is SomeItem and it has a property like Name , you can use LINQ like this:

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;
string result = string.Empty;

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

txtReceipt.Text = result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM