繁体   English   中英

将列添加到实体框架数据绑定的数据网格视图

[英]Add column to Entity framework databound datagridview

在我的软件中,我做了一些实体:

public abstract class Product 
{
    public int ProductId { get; set; }
    public string name{ get; set; }
}
public class type1 :Product
{
    public int number{ get; set; }
    public string extradata{ get; set; }
    public bool uitgeleend { get; set; }
}
public class type2 : Product
{
    [Display(Name = "Merk en type")]
    public string type { get; set; }
    public string extradata{ get; set; }
    public bool available{ get; set; }
}

为了显示这是一个datagridview,我有这个表达式:

var results =db.producten.Where(c => c is type1|| c is type2).ToList();
        dataGridView1.DataSource = results;

问题是,EF将额外数据作为类型1的额外数据放入表中,对于类型2的额外数据将其放在表格中。 当我想通过以下方式将我的额外数据添加到我的gridview中时

this.dataGridView1.Columns["extradata"].Visible = true;

我得到一个nullreferenceException,因为type2不包含这样的列。 如何在我的datagridview中显示该列,而又无需过多更改实体?

您可以为此目的使用DataTable

从列表中创建一个DataTable ,根据需要添加更多列,将DataTable绑定到DataGridView

你完成了。

您可以尝试一下,我认为:
不知道只是尝试一下:

var results =db.producten.Where(c => c is type1|| c is type2).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM