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

前端 未结 1 1532
孤独总比滥情好
孤独总比滥情好 2020-12-06 15:05

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

  • Estimates has columns such as \"
相关标签:
1条回答
  • 2020-12-06 15:43

    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:

    • Show Properties of a Navigation Property in DataGridView (Second Level Properties)
    0 讨论(0)
提交回复
热议问题