fwilson
fwilson

Reputation: 57

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

Upvotes: 3

Views: 10522

Answers (4)

Vimal CK
Vimal CK

Reputation: 3563

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; 

Upvotes: 1

Nick
Nick

Reputation: 4212

string result = string.Empty;

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

txtReceipt.Text = result;

Upvotes: 0

Matten
Matten

Reputation: 17603

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;

Upvotes: 0

David Pilkington
David Pilkington

Reputation: 13618

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

Upvotes: 1

Related Questions