How to bind a Navigation Property (second level pr

2019-01-15 11:13发布

I have used two entity classes for binding values into DataGridView. One is Estimates and Companies.

  • Estimates has columns such as "Id, Estimate Number, Estimate Amount, CompanyId".
  • Companies has columns such as "Id, Company Name, Address"

I have created two BindingSource such as EstimateBindingSource and CompanyBindingSource.

  1. CompanyBindingSource has DataSource as EstimateBindingSource and DataMember as Estimates
  2. EstimateBindingSource has DataSource as Estimates entity Class and no DataMember defined.

I have bound the EstimateBindingSource into the DataGridView using grid DataSource.

Here, I need to show Estimate number, Estimate Amount and Company Name in DataGridView.. I have't able to achieve this.

Note: I do not do any code behind logic to do this.. Need to achieve this only using design.

1条回答
smile是对你的礼貌
2楼-- · 2019-01-15 11:13

Options to show Second Level Properties in DataGridView

To show a sub property of your navigation property you can use either of these options:

  1. Use a DataGridViewComboBox column and bind it to CompanyId and set it's DataSource to list of companies, and DisplayMember property to Name property of company and ValueMember to Id property of company.

  2. Override ToString() method of Company class and return Name of company. Then show Company navigation property in grid.

  3. Create a CompanyName property for your Estimate which returns its Company.Name value and show CompanyName in grid.

  4. Using CellFormatting event of DataGridView and set e.Value to desired value (company name) you want to display in cell.

  5. Shape your Estimates list using a Linq query or use a ViewModel and pass the result to data grid view.

  6. Create a TypeDescriptor for your Estimate type to resolve second level properties. . To show a property of company instead of company id, you can use a DataGridViewComboBoxColumn.

Using ComboBox Column

Since you requested for a mechanism which uses designer without writing code I describe this option more. Here is settings you should perform:

  • EstimatesBindingSource should bind to a list of Estimates
  • The DataGridView should bind to EstimatesBindingSource
  • CompanyBindingSource is only used as data source of the combo box column and should be filled using a list of Companies
  • To show CompanyName in Estimates list, it's enough to use a DataGridViewComboBoxColumn and set it's DataSource to list of companies and set the DisplayMember to CompanyName and it's value member to Id. And bind it to CompanyId field of Estimate.

Also if your requirement is to don't show it as ComboBox, simply set DisplayStyle property of DataGridViewComboBoxColumn to Nothing. It removes dropdown style.

You also may find this post helpful:

查看更多
登录 后发表回答