问题
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.
CompanyBindingSourcehas DataSource asEstimateBindingSourceand DataMember asEstimatesEstimateBindingSourcehas DataSource asEstimatesentity 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:
Options to show Second Level Properties in DataGridView
To show a sub property of your navigation property you can use either of these options:
Use a
DataGridViewComboBoxcolumn and bind it toCompanyIdand set it'sDataSourceto list of companies, andDisplayMemberproperty toNameproperty of company andValueMembertoIdproperty of company.Override
ToString()method ofCompanyclass and returnNameof company. Then showCompanynavigation property in grid.Create a
CompanyNameproperty for yourEstimatewhich returns itsCompany.Namevalue and showCompanyNamein grid.Using
CellFormattingevent ofDataGridViewand sete.Valueto desired value (company name) you want to display in cell.Shape your Estimates list using a
Linqquery or use aViewModeland pass the result to data grid view.Create a
TypeDescriptorfor yourEstimatetype to resolve second level properties. . To show a property of company instead of company id, you can use aDataGridViewComboBoxColumn.
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:
EstimatesBindingSourceshould bind to a list ofEstimates- The
DataGridViewshould bind toEstimatesBindingSource CompanyBindingSourceis only used as data source of the combo box column and should be filled using a list ofCompanies- To show
CompanyNameinEstimateslist, it's enough to use aDataGridViewComboBoxColumnand set it'sDataSourceto list of companies and set theDisplayMembertoCompanyNameand it's value member toId. And bind it toCompanyIdfield ofEstimate.
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:
- Show Properties of a Navigation Property in DataGridView (Second Level Properties)
来源:https://stackoverflow.com/questions/36469904/how-to-bind-a-navigation-property-second-level-properties-in-datagridview-usin