尝试在数据网格中存储列表
本文关键字:存储 列表 网格 数据网 数据 | 更新日期: 2023-09-27 17:56:10
我正在尝试制作一个程序,该程序具有一个数据网格,该网格显示在每行,披萨的成分列表,披萨名称和披萨的价格。我可以让数据网格显示名称和价格,但我无法让它显示成分列表。数据网格的数据源是名为 Pizza 的类的绑定列表。
class Pizza
{
private List<Ingredients> ingredientList_;
private string pizzaName_;
private decimal retailPrice_;
public Pizza(List<Ingredients> ingredientList, string pizzaName, decimal retailPrice)
{
ingredientList_ = ingredientList;
pizzaName_ = pizzaName;
retailPrice_ = retailPrice;
}
它具有基本的获取和设置属性。我还有一个成分课。
class Ingredients
{
private string name_;
private int servingSize_;
private int energyValue_;
private decimal purchasePrice_;
private bool isVegetarian_;
public Ingredients(string name, int servingSize, int energyValue, decimal purchasePrice, bool isVegetarian)
{
name_ = name;
servingSize_ = servingSize;
energyValue_ = energyValue;
purchasePrice_ = purchasePrice;
isVegetarian_ = isVegetarian;
}
具有基本的获取和设置属性。
在我的表单代码中,我有:
private BindingList<Pizza> pizzaList_;
pizzaList_ = new BindingList<Pizza>();
dataGridViewPizzaMenu.DataSource = pizzaList_;
现在我的问题是,当我单击比萨饼时,我正在尝试使用组合框列来显示比萨饼中的成分。但我似乎无法为成分创建绑定列,只能创建披萨名称和披萨价格。我错过了什么还是我试图做的事情是不可能的?
你所做的一切都是正确的。我认为问题在于 DataGridView 在设计或运行时的设置方式。
如果您转到此答案,您可以看到需要采取的步骤:将数组的所有元素添加到数据网格视图行,但一个元素除外
- 绑定
第一个组合框列的诀窍是绑定源。在设计时>右键单击 DataGridView>选择"编辑列">选择第一列>选择"数据源">单击"添加项目数据源">选择"对象>",然后勾选
Ingredients
类并单击"完成"。若要将第一个组合框列设置为"成分列表"
DataMember
,则需要选择已添加的"IngredientsDataBindingSource"控件(略低于窗体设计的表面 - 在灰色区域中)- 第 2 和第 3 个为披萨名称和零售价格添加两个文本框列,并相应地设置
DataPropertyName
。
pizzaList_ = new BindingList<Pizza>();
//Insert code to populate the List of Pizza's and Ingredients
dataGridViewPizzaMenu.AutoGenerateColumns = false;
dataGridViewPizzaMenu.DataSource = pizzaList_;
ingredientsDataBindingSource.DataSource = pizzaList_.ingredientsList_;
ps 在我上面提到的链接中有一个可下载的示例。
您可以创建一个组合框并设置此事件,接下来,使用 Datagridview1.Row.Add 方法在 Datagridview 中插入一行。但在此之前,您应该使用带有一些单元格的DatagridviewRow,该行的自己的单元格是DataGrifViewComboBoxCell。
祝你好运。。。
为了将组合框放在第三个字段中,您必须创建前两个作为数据网格视图项:
DataGridViewRow RowSample = new DataGridViewRow();
DataGridViewComboBoxCell pizzaItem = new DataGridViewComboBoxCell();
pizzaItem.DataSource = pizzaList_;
pizzaItem.Value = pizzaList_[0];
DataGridViewCell pizzaName = new DataGridViewTextBoxCell();
pizzaName.Value = pizza.pizzaName; // creating the text cell
DataGridViewCell pizzaPrice = new DataGridViewTextBoxCell();
pizzaPrice.Value = pizza.pizzaPrice;; // creating the text cell
RowSample.Cells.Add(pizzaName);
RowSample.Cells.Add(pizzaPrice);
RowSample.Cells.Add(pizzaItem);
SampleGridView.Rows.Add(RowSample);
现在,RowSample将具有3个字段的数据网格视图添加到您中,第三个字段是组合框。
在表单加载事件上
ingredientList_ = context.Ingredients.OrderBy(p => p.ingredientName).ToList();
FillCombo();
创建一个填充组合的方法
private void FillCombo()
{
IngredientBindingSource.DataSource = ingredientList_;
}