如何使用带有扩展对象的列表将数据绑定到数据网格视图

时间:2018-10-26 09:03:02

标签: c# .net winforms datagridview

我尝试将List<Member>绑定到DataGrid,但是我不知道该怎么做。 我有两节课:

public class Member
{
    public int id { get; set; }
    public string name { get; set; }
    public double salary { get; set; }
}

public class Player : Member
{
    public double bonus { get; set; }
}

List<Member>包含MemberPlayer对象。我知道我应该在需要的地方将Member对象投射到Player上。我不知道该怎么做。

如果我绑定List <Member>,则如果对象实际上是Member,则它仅显示Player变量及其值,而没有其他字段。我应该对其进行迭代以及如何进行迭代?

这就是我现在收集它们的方式:

List<Member> list = db.Members.ToList();
dataGridView1.DataSource = list;

返回为:

Member
Player 

Output

期望:

Expect

4 个答案:

答案 0 :(得分:2)

如果您使用List集合,则需要给出一种类型,因此可以尝试让List<Member>转换为List<Player>

根据您的预期结果bonus属性可以为double?

public class Member
{
    public int id { get; set; }
    public string name { get; set; }
    public double salary { get; set; }
}

public class Player : Member
{
    public double? bonus { get; set; }
}
Player列表的girdview上

绑定

List<Player> list = db.Members.Select(x => {
Player p = x as Player;

    if (p != null)
        return p;

    return new Player()
    {
        id = x.id,
        name = x.name,
        salary = x.salary
    };
});
dataGridView1.DataSource = list;

答案 1 :(得分:1)

除非明确添加列(例如,在Designer中),否则将从绑定列表的元素类型自动创建列。因为在您的示例中这是Member,所以网格将没有Salary列。因此,也许您可​​以创建一些这样创建的转换类的列表:

public class MemberViewModel
{
    private Member member;
    public MemberViewModel(Member member) => this.member = member;

    public int Id => member.id;
    public string Name => member.name;
    public double Salary => member.salary;
    public double? Bonus => member is Player player ? player.bonus : default(double?);
}

然后:

dataGridView1.DataSource = myOriginalMemberList.Select(member => new MemberViewModel(member)).ToList();

答案 2 :(得分:0)

您必须从Player而不是Member

检索数据
List<Player> list = db.Players.ToList();

答案 3 :(得分:0)

您可以尝试将Member转换为Player,如果成功,则可以将该值添加到网格中:

foreach(var record in list)
{
    var player = record as Player; // try to cast your record to Player
    if (player != null)
    {
        // if it is a player do something with it
        ...
    }
}

希望这会让您了解如何管理大小写并将Player添加到网格。