繁体   English   中英

如何使用BindingSource绑定DataGridView中的导航属性(二级属性)?

[英]How to bind a Navigation Property (second level properties) in DataGridView using BindingSource?

我使用了两个实体类将值绑定到DataGridView 一个是估计和公司。

  • 估算有“Id,Estimate Number,Estimate Amount,CompanyId”等列
  • 公司有“Id,Company Name,Address”等栏目

我创建了两个BindingSource例如EstimateBindingSourceCompanyBindingSource

  1. CompanyBindingSourceDataSource作为EstimateBindingSource ,将DataMember作为Estimates
  2. EstimateBindingSourceDataSource作为Estimates实体类,并且没有定义DataMember

我已使用网格DataSourceEstimateBindingSource绑定到DataGridView

在这里,我需要在DataGridView中显示估计数字,估计金额和公司名称 。我无法实现这一目标。

注意: 我没有做任何逻辑背后的代码来做到这一点。需要只使用设计来实现这一点。

用于在DataGridView中显示第二级属性的选项

要显示导航属性的子属性,可以使用以下任一选项:

  1. 使用DataGridViewComboBox列并将其绑定到CompanyId并将其DataSource设置为公司列表,将DisplayMember属性设置为公司的Name属性,将ValueMember设置为公司的Id属性。

  2. 覆盖Company类的ToString()方法并返回公司Name 然后在网格中显示Company导航属性。

  3. Estimate创建一个CompanyName属性,该属性返回其Company.Name值并在网格中显示CompanyName

  4. 使用DataGridView CellFormatting事件并将e.Value设置为要在单元格中显示的所需值(公司名称)。

  5. 使用Linq查询ViewModel您的Estimates列表或使用ViewModel并将结果传递给数据网格视图。

  6. Estimate类型创建TypeDescriptor以解析二级属性。 要显示公司的属性而不是公司ID,可以使用DataGridViewComboBoxColumn

使用ComboBox列

由于您要求使用设计器而不编写代码的机制,因此我更多地描述了此选项。 以下是您应该执行的设置:

  • EstimatesBindingSource应绑定到Estimates列表
  • DataGridView应绑定到EstimatesBindingSource
  • CompanyBindingSource仅用作组合框列的数据源,应使用Companies列表填充
  • 要在Estimates列表中显示CompanyName ,只需使用DataGridViewComboBoxColumn并将其DataSource设置为公司列表,并将DisplayMember设置为CompanyName ,将其value值设置为Id 并将其绑定到Estimate CompanyId字段。

此外,如果您的要求是不将其显示为ComboBox ,只需将DataGridViewComboBoxColumn DisplayStyle属性设置为Nothing 它删除了下拉样式。

你也可以发现这篇文章有用:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM