如何在DataGridView';中绑定导航属性(二级模型的两个属性);s使用BindingSource的单列

本文关键字:属性 单列 模型 二级 BindingSource 使用 两个 DataGridView 导航 绑定 | 更新日期: 2024-10-23 23:59:20

我遇到了使用绑定源在网格视图中显示值的问题。我有两个型号,分别是CompanyPartners

  1. 我在公司模型中有CCD_ 3
  2. Partner模型有CCD_ 4和CCD_

我已经显示了公司信息和合作伙伴的名字如上所示。

现在,我需要将合作伙伴的名字和姓氏在单列中显示为PartnerName。有人能帮我解决这个问题吗?

如何在DataGridView';中绑定导航属性(二级模型的两个属性);s使用BindingSource的单列

选项1-CellFormatting

作为一个选项,您可以使用DataGridViewCellFormatting事件并显示所需值:

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);
}

生成返回格式化全名的属性,并将其绑定到网格单元格。您可以使用多绑定,但这需要额外的转换器来返回(作为您的附加属性)格式化的字符串,例如。