简体   繁体   中英

Formatting a string for a listbox in C#

I'll start off by saying that the listbox is a requirement for a class project. I'm just trying to spiff it up and make it look nicer by formatting a string before adding it to a list box. I have an override for Product.ToString() that formats the string, but when I add it to the list box, the formatting dissapears.

ToString method in Product class:

public override string ToString()
{
    string newFormat = string.Format("{0,0}{1,20}", Name, Price);
    return newFormat;
}

Update method:

protected void updateLists()
{
    availableProducts_LB.Items.Clear();
    foreach (Product p in customer.AvailableProducts)
        availableProducts_LB.Items.Add(p.ToString());

    shoppingCart_LB.Items.Clear();
    foreach (Product p in customer.shoppingCartList)
        shoppingCart_LB.Items.Add(p.ToString());
}

Just add your Product instances directly to the ListBox (don't call ToString):

availableProducts_LB.Items.Clear();
foreach (Product p in customer.AvailableProducts)
    availableProducts_LB.Items.Add(p);

The ListBox will use the Product.ToString method to display the items in the list.

Then put a breakpoint on the return statement in ToString to make sure it is the value you are expecting.

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