![](/img/trans.png)
[英]How to bind a Navigation Property (second level properties) in DataGridView using BindingSource?
[英]How to bind Navigation Property (second level model's two properties) in DataGridView's single column using BindingSource?
我遇到了使用綁定源在網格視圖中顯示值的問題。 我有兩個模型作為Company
和Partners
。
PartnerId
, FirstName
和LastName
。 我已經顯示了公司信息和合作伙伴的名字,如上所示。
現在,我需要在單列中將Partner的名字和姓氏顯示為PartnerName
。 任何人都可以幫我解決這個問題嗎?
選項1 - CellFormatting
作為選項,您可以使用DataGridView
CellFormatting
事件並顯示所需的值:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//I Suppose you want to show full name in column at index 3
if(e.RowIndex>=0 && e.ColumnIndex==3)
{
var company = (Company)(this.dataGridView1.Rows[e.RowIndex].DataBoundItem);
if (company != null && company.Partner != null)
e.Value = string.Format("{0} {1}", company.Partner.FirstName,
company.Partner.LastName);
}
}
選項2 - ToString()
作為另一種選擇,您可以覆蓋Partner
類的ToString()
方法並在列中顯示Partner
:
public override string ToString()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
使屬性返回格式化全名並將此綁定到網格單元格。 您可以使用多綁定,但需要額外的轉換器,例如,返回(作為您的附加屬性)格式化字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.