将其他项添加到列表框中

时间:2012-04-10 20:03:52

标签: c#

我在列表框中添加项目时遇到了困难。我想在列表框的开头添加一个项目作为我的“默认”项目,但是我还将使用.DataSource添加列表中的项目列表...由于某种原因,应用程序每当崩溃我尝试同时添加List和默认项目中的项目。我正在尝试使用以下方法添加项目:

`productList.DataSource = salesManager.Products;
productList.DisplayMember = "IdAndName";
productList.ValueMember = "Id";
productList.Items.Insert(0, "ALL");`
但由于某种原因VS不会让我。我也发现了这种方法并尝试应用它:

public void AddListLine(string lineIn)
    {
        productList.Items.Insert(0, "ALL");
        ((CurrencyManager)productList.BindingContext[productList]).Refresh();
    }

然而它不起作用。有什么好主意吗?谢谢!

1 个答案:

答案 0 :(得分:2)

它不起作用的原因是因为您正在尝试添加String类型的对象,其余的是(我假设)类型Product或类似的东西。运行时尝试访问要显示的属性IdAndName,以及新列表项的显示和值属性的属性Id,它们不存在。

考虑添加某种“空白”Product对象。

public void AddListLine(string lineIn)
    {
        productList.Items.Insert(0, new Product { Id = "ALL", IdAndName = "ALL" });
        ((CurrencyManager)productList.BindingContext[productList]).Refresh();
    }