我尝试将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>
包含Member
和Player
对象。我知道我应该在需要的地方将Member
对象投射到Player
上。我不知道该怎么做。
如果我绑定List <Member>
,则如果对象实际上是Member
,则它仅显示Player
变量及其值,而没有其他字段。我应该对其进行迭代以及如何进行迭代?
这就是我现在收集它们的方式:
List<Member> list = db.Members.ToList();
dataGridView1.DataSource = list;
返回为:
Member
Player
期望:
答案 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添加到网格。