gpt4 book ai didi

data-binding - 将组合框列数据绑定(bind)到每行的数据 GridView (不是整个列)

转载 作者:行者123 更新时间:2023-12-01 01:29:10 25 4
gpt4 key购买 nike

有一些关于这个的帖子,但经过几个小时的搜索,我仍然找不到我需要的东西。

以下帖子中的答案几乎让我得到了我想要的:
Combobox for Foreign Key in DataGridView

问题一:

从产品具有许多许可证的示例开始,我的数据库映射都是多对一关系,这意味着我的许可证类包含对产品类的引用。 License 类没有 ProductId 的属性,因为它可以通过 Product 引用检索。我不想用对 Product 和 ProductId 属性的引用来混淆 License 类,只是为了使 UI 中的绑定(bind)更容易。

因此,我无法设置 DataPropertyName到一个 Id 字段。它必须是类引用名称,如下所示:

DataGridViewComboBoxColumn dataGridViewComboBoxColumn = 
(DataGridViewComboBoxColumn)myDataGridView.Columns("LicenseComboBoxColumn");

dataGridViewComboBoxColumn.DataPropertyName = "License"; // not LicenseID

****更新****
通过将 Product.Id 指定为 DataPropertyName ,我能够在不创建 ProductId 属性的情况下使其部分工作,如下所示:
dataGridViewComboBoxColumn.DataPropertyName = "License.Id";

但是,这样做时,它破坏了数据绑定(bind),导致我手动获取和设置单元格值。

我还看到了有关绑定(bind)到 DataGridView 单元格的帖子,但是当我这样做时数据绑定(bind)会中断,并且数据源本身永远不会更新:
// populate the combo box with Products for each License

foreach (DataGridViewRow row in myDataGridViewProducts.Rows)
{
IProduct myProduct = row.DataBoundItem as IProduct;
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells("myProductCol");
cell.DataSource = getListOfILicenseObjectsFromDao(myProduct.Id);
cell.Value = myProduct.License.Id;
}

也许我做错了什么,或者也许有不同的方式。有人可以在这里帮忙吗?

问题二:

如何为每个产品显示不同的许可证列表?
换句话说,许可证的组合框列表对于网格中的每个产品都是不同的。我想使用数据绑定(bind)来做到这一点,所以我不必自己获取和设置值。

最佳答案

我自己找到了答案。不久前我遇到了同样的问题,并在我挖出的一些旧代码中找到了解决方案。解决方案是将 Self 属性添加到我想在组合框中进行数据绑定(bind)的对象(在上面的示例中,它将是 License 类),并将该属性用作 ValueMember,如下所示:

foreach (DataGridViewRow row in myDataGridViewProducts.Rows) 
{
IProduct myProduct = row.DataBoundItem as IProduct;
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells("myProductCol");
cell.DataSource = getListOfILicenseObjectsFromDao(myProduct.Id);
cell.DataPropertyName = "License";
cell.DisplayMember = "Name";
cell.ValueMember = "Self"; // key to getting the databinding to work
// no need to set cell.Value anymore!
}

License 类现在看起来像这样:
Public class License
{
public string Name
{
get; set;
}

public ILicense Self
{
get { return this; }
}

// ... more properties
}

当然,我不得不用一个名为 Self 的属性来“搞砸”业务类,但这比在 Product 类 IMO 中同时引用 License 和 LicenseId 属性要好得多(程序员不会感到困惑)。此外,它使 UI 代码更加简单,因为无需手动获取和设置值 - 只需数据绑定(bind)并完成。

关于data-binding - 将组合框列数据绑定(bind)到每行的数据 GridView (不是整个列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5916312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com