c# - 如何使用 BindingSource 在 DataGridView 的单列中绑定(bind)导航属性(二级模型的两个属性)?

标签 c# winforms entity-framework datagridview bindingsource

我在使用绑定(bind)源显示 GridView 中的值时遇到了问题。我有两个模型,分别是 CompanyPartners

  1. 我在公司模型中有 PartnerId
  2. 合作伙伴模型有 FirstNameLastName

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

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

最佳答案

选项 1 - 单元格格式化

作为一个选项,您可以使用 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);
}

关于c# - 如何使用 BindingSource 在 DataGridView 的单列中绑定(bind)导航属性(二级模型的两个属性)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760909/

相关文章:

c# - 键入时将文本设置为全部大写

c# - 在指定位置打开一个 "ColorDialog"对话框

c# - 将一个 HttpRequest 中的多个事件发布到 Google Analytics

c# - 如何从此 json 对象获取值?

C# File.Copy 配额不足

c# - 添加行时保持 TextBox 滚动位置

c# - 如何将.Net Core应用程序连接到Azure SQL数据库

c# - Entity Framework 级联删除多列键

c# - ActionResult 中的 MVC 字符串

c# - 无法在 ASP.NET 中更新 cookie