简体   繁体   English

在C#中格式化列表框的字符串

[英]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. 我有一个Product.ToString()重写来格式化字符串,但是当我将其添加到列表框中时,格式化消失了。

ToString method in Product class: Product类中的ToString方法:

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): 只需将您的Product实例直接添加到ListBox中(不要调用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. ListBox将使用Product.ToString方法显示列表中的项目。

Then put a breakpoint on the return statement in ToString to make sure it is the value you are expecting. 然后在ToString的return语句上放置一个断点,以确保它是您期望的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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