我有一个Collection Class,它是一个放置List<Ingredient>
对象的类,Ingredient对象列表的内容使用绑定显示在CheckListBox
中。
我尝试做的是当用户点击其中一个列表项时,该特定项目中的信息被复制到另一个名为List<Pizza> myPizza
的列表中,然后该列表将显示在列表中。我希望所有数据进入它的原因是因为一旦进入List<Pizza> myPizza
,我会对数据做更多的事情。
我试过这样做,但似乎没有效果,下面是CollectionClass
,窗体和成分类。我没有打扰披萨级,因为它与成分类相同
我知道如何使用item将它添加到列表框中,但我真的想将它添加到List中,然后将List添加到ListBox。
我希望这是有道理的,有点新的编程。感谢。
成分类。
public partial class Form1 : Form
{
//List<Ingredient> myIngredient = new List<Ingredient>();
List<Pizza> myPizza = new List<Pizza>();
CollectionClass myCollections = new CollectionClass();
public Form1()
{
InitializeComponent();
myCollections.createList();
checkedListBoxIngredients.DataSource = new BindingSource(myCollections.myIngredient, null);
checkedListBoxIngredients.DisplayMember = "DisplayName";
}
private void checkedListBoxIngredients_ItemCheck(object sender, ItemCheckEventArgs e)
{
foreach (Pizza pizza in myPizza)
{
checkedListBoxIngredients.Items.Add(pizza.ToppingName);
checkedListBoxIngredients.Items.Add(pizza.UnitName);
checkedListBoxIngredients.Items.Add(pizza.Cost);
checkedListBoxIngredients.Items.Add(pizza.DescriptionName);
}
if (e.NewValue == CheckState.Checked)
{
yourPizza.DataSource = new BindingSource(myPizza, null);
yourPizza.DisplayMember = "DisplayName";
}
}
}
成分类别。
public class Ingredient
{
public string ToppingName { get; set; }
public string UnitName { get; set; }
public int Cost { get; set; }
public string DescriptionName { get; set; }
public Ingredient(string pizzaToppingName, string pizzaToppingUnit, int pizzaCost, string pizzaDescription)
{
ToppingName = pizzaToppingName;
UnitName = pizzaToppingUnit;
Cost = pizzaCost;
DescriptionName = pizzaDescription;
}
public string DisplayName
{
get
{
return ToppingName + " $"+Cost;
}
}
public override string ToString()
{
return ToppingName;
}
}
CollectionClass。
public class CollectionClass
{
public List<Ingredient> myIngredient = new List<Ingredient>();
public void createList()
{
myIngredient.Add(new Ingredient("Cheese", "grams", 3, "grab cheese and sprinkle on top of pizza"));
myIngredient.Add(new Ingredient("Olives", "grams", 2, "cut up olives and sprickle on pizza"));
myIngredient.Add(new Ingredient("Ham", "grams", 1, "spread cut up ham over pizza"));
myIngredient.Add(new Ingredient("Pineapple", "grams", 1, "spread cut up chunks over pizza"));
myIngredient.Add(new Ingredient("Pepperoni", "pieces", 1, "place slices on pepperoni on pizza"));
myIngredient.Add(new Ingredient("Onion", "handfuls", 1, "sprinkle cut up onion on pizza, try not to cry"));
myIngredient.Add(new Ingredient("Peppers", "grams", 1, "sprinkle cut up peppers on pizza"));
myIngredient.Add(new Ingredient("Anchovy", "grams", 1, "place on top of pizza"));
myIngredient.Add(new Ingredient("Mushrooms", "grams", 1, "put gently on top of pizza"));
}
public void displayList()
{
foreach (Ingredient ingred in myIngredient)
if (ingred != null)
{
Console.WriteLine("{0} {1} ${2}.00, {3}",
ingred.ToppingName, ingred.UnitName, ingred.Cost,
ingred.DescriptionName);
}
}
}