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

2
  • 1
    +1 for showing your attempt and being clear about what you're trying to achieve. Commented Nov 5, 2013 at 8:36
  • You will need to loop over your ListBox collection. Commented Nov 5, 2013 at 8:36

4 Answers 4

1

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; 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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;

2 Comments

sorry for my low knowledge, but what is <SomeItem>, because when i put it in my code an error shows up saying " the type or namespace name 'SomeItem' could not be found. what do i do?
It is the type of the item you put into the listbox. If these are only strings, use string instead of SomeItem, for example.
0
string result = string.Empty;

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

txtReceipt.Text = result;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.