我在使用绑定(bind)源显示 GridView 中的值时遇到了问题。我有两个模型,分别是 Company
和 Partners
。
- 我在公司模型中有
PartnerId
, - 合作伙伴模型有
FirstName
和LastName
。
如上所示,我已经显示了公司信息和合作伙伴的名字。
现在,我需要在单个列中将合作伙伴的名字和姓氏显示为 PartnerName
。谁能帮我解决这个问题?
最佳答案
选项 1 - 单元格格式化
作为一个选项,您可以使用 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);
}
关于c# - 如何使用 BindingSource 在 DataGridView 的单列中绑定(bind)导航属性(二级模型的两个属性)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760909/