4

有几个关于此的帖子,但经过几个小时的搜索,我仍然无法找到我所需要的。将数据绑定列数据绑定到每行datagridview(不是整列)

在以下职位的回答几乎让我什么,我想: Combobox for Foreign Key in DataGridView

问题1:

去关闭该例子,其中一个产品有很多许可证,我的数据库映射都是多对一这意味着我的许可证类拥有对产品类的引用。该License类没有ProductId的属性,因为可以通过产品参考获取该属性。我不想用引用Product和ProductId属性的方法来清理许可证类,以便更容易地在UI中进行绑定。

因此,我无法将DataPropertyName设置为Id字段。它需要的类引用名字,像这样:

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

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

**** ****更新我 能得到这个没有通过指定Product.Id作为创建产品ID属性部分工作DataPropertyName像这样:

dataGridViewComboBoxColumn.DataPropertyName = "License.Id"; 

但是,这样做的时候,它打破了这引起了我的手工获取和设置单元格的值数据绑定。

我也看到了帖子关于绑定到DataGridView细胞,但数据绑定符,当我做到这一点,数据源本身从不更新:

// 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; 
} 

也许我做错了什么,或者也许有一种不同的方式。任何人都可以帮忙吗?

问题2:

如何显示牌照为每个产品不同的名单? 换句话说,对于网格中的每个产品,许可证的组合框列表将不同。我想用数据绑定来完成这个工作,所以我不必亲自去设置这些值。

回答

4

我自己找到了答案。前一段时间我遇到了同样的问题,并在我挖出的一些旧代码中找到了解决方案。解决的办法是增加一个自属性我想数据绑定到在组合框(在上面的例子中这将是许可类)的对象,并使用该属性作为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! 
} 

许可证类现在看起来是这样的:

Public class License 
{ 
    public string Name 
    { 
     get; set; 
    } 

    public ILicense Self 
    { 
     get { return this; } 
    } 

    // ... more properties 
} 

授予我不得不“粪”了商务类与属性命名的自我,但是这不是既具有参考执照和一个更好的(容易混淆的程序员)产品类IMO中的LicenseId属性。此外,它使UI代码更加简单,因为不需要手动获取和设置值 - 只需绑定数据并完成即可。