【问题标题】:How to bind two tables to Datagridview using entity framework C#如何使用实体框架 C# 将两个表绑定到 Datagridview
【发布时间】:2015-07-04 07:57:04
【问题描述】:

我有两个 Tables Estate 和 EstateType。如何将这两个表绑定到一个数据网格? 我尝试了类似的方法,但这不起作用。

 var getAllEst = (from ee in AgencyContext.Estate join eeT in AgencyContext.EstateType
                         on ee.EstateID equals eeT.EstateID select ee).ToList();

dataGridView1.DataSource = getAllEst;

它给了我数字而不是字符串值 EstateType、Landscape、Description

正如@tpayne84 建议的那样,我添加了新列,但现在我得到的是这个而不是值:

这是我使用的代码:

var getAllEst = (from ee in AgencyContext.Estate join eeT in AgencyContext.EstateType
                         on ee.EstateID equals eeT.EstateID select ee).ToList();
        DataGridViewTextBoxColumn EstateType1 = new DataGridViewTextBoxColumn();
        DataGridViewTextBoxColumn LandScape1 = new DataGridViewTextBoxColumn();
        DataGridViewTextBoxColumn Description1 = new DataGridViewTextBoxColumn();
        EstateType1.DataPropertyName = "EstateType";
        LandScape1.DataPropertyName = "LandScape";
        Description1.DataPropertyName = "Discription";
        dataGridView1.Columns.Add(EstateType1);
        dataGridView1.Columns.Add(LandScape1);
        dataGridView1.Columns.Add(Description1);
        dataGridView1.DataSource = getAllEst;

【问题讨论】:

  • 解释你说“这行不通”的意思。你得到一个错误或只是不正确的输出?
  • 我更新了问题。

标签: c# winforms linq entity-framework datagridview


【解决方案1】:

问题看起来像您显示的是引用对象的外键 ID,而不是您希望显示的对象上的属性。

这是因为您允许 DataGridView 为您生成列。

要解决这个问题,您需要自己创建列:

DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
// Where "Name" is the String representation of the Property on the
// Object that you want to display.
nameColumn.DataPropertyName = "Name";

【讨论】:

    【解决方案2】:

    首先,您的查询

    var getAllEst = (from ee in AgencyContext.Estate 
                     join eeT in AgencyContext.EstateType
                         on ee.EstateID equals eeT.EstateID select ee).ToList();
    

    只会使用内部连接选择具有关联EstateTypeAgencyContext.Estate 对象...除非您的Estate classEstateType 有一些导航属性。如果你有类似的东西:

    class Estate
    {
        // ...other properties
    
        // I'm guessing the relationship here...
        public virtual EstateType EstateType { get; set; } 
    }
    

    那么您将能够通过该属性访问EstateType 属性。

    不幸的是,DataGridViewdoesn't seem to support binding to child properties 所以你不能设置column.DataPropertyName = EstateType.SomeProperty,但你可以通过覆盖EstateType.ToString() 或处理DataGridView 上的CellFormatting 事件来解决这个问题。

    【讨论】:

      猜你喜欢
      • 2011-08-13
      • 2011-12-05
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多