【问题标题】:Add multiple items into a ListBox from multiple TextBoxes将多个项目从多个文本框添加到列表框中
【发布时间】:2017-03-31 10:42:52
【问题描述】:

我想为产品创建一个购物篮,用户输入产品名称、数量和价格,然后将其放入同一行的列表框中。这是我目前所拥有的

private void addToBasket_Click(object sender, EventArgs e)
    {

        string product = productName.Text;
        decimal quan = quantity.Value;
        int quant = Convert.ToInt32(quan);
        string p = this.price.Text;
        int price = Convert.ToInt32(p);
        basket.Items.Add(new ListBoxItem(product, quan, price));
    }
}

internal class ListBoxItem
{
    private string product;
    private decimal quan;
    private int price;

    public ListBoxItem(string product, decimal quan, int price)
    {
        this.product = product;
        this.quan = quan;
        this.price = price;
    }
}

当我单击添加时,它会放入列表框中:BasketForm.ListBoxItem 没有与我在文本框中输入的内容相关的值

【问题讨论】:

  • 您可能需要设置 ListBoxItem.DisplayMember 和 ValueMember 才能查看对象类型以外的任何内容。

标签: c# textbox listbox


【解决方案1】:

当对象绑定到(列表框)控件时,该控件将默认使用 ToString 方法来显示值。您可以在 ListBoxItem 类中重写上述方法,以使任何控件显示数量、项目名称和单价:

    public override string ToString()
    {
        return string.Format("{0}x {1} @{2}", quan, product, price);
    }

【讨论】:

  • 在你的课堂上。每个类都实现了 ToString 方法,这里我们重写它以返回对象的属性。或者,正如@JayF1 所建议的,您可以将 ListBoxes DisplayMember 设置为产品名称(或其他任何名称)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多