C# – how to add items from listbox to textbox c#

clistboxtextbox

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

Best Answer

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;