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
.
CompanyBindingSource
has DataSource as EstimateBindingSource
and DataMember as Estimates
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.
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 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.
Override ToString()
method of Company
class and return Name
of company. Then show Company
navigation property in grid.
Create a CompanyName
property for your Estimate
which returns its Company.Name
value and show CompanyName
in grid.
Using CellFormatting
event of DataGridView
and set e.Value
to desired value (company name) you want to display in cell.
Shape your Estimates list using a Linq
query or use a ViewModel
and pass the result to data grid view.
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:
- Show Properties of a Navigation Property in DataGridView (Second Level Properties)