我正在使用Entity Framework 6来建模数据库中的客户端列表。我将集合成功绑定到列表框。我无法弄清楚如何使用对象中的多个字段绑定到Windows窗体ListBox的DisplayMember
属性。
这有效......
myLsiTBox.DataSource = context.Clients.ToList();
myLsiTBox.DisplayMember = "CompanyName";
myLsiTBox.ValueMember = "id";
这失败了......
myLsiTBox.DataSource = context.Clients.ToList();
myLsiTBox.DisplayMember = "CompanyName" + "-" + "LastName" + " - " + "FirstName";
myLsiTBox.ValueMember = "id";
如何显示ListBox中多个字段的内容?
答案 0 :(得分:0)
如果这是您的客户:
public class Client
{
public string CompanyName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
您可以创建ClientViewModel,然后将列表框数据源绑定到ClientViewModel列表,并将DisplayMember设置为“FullDetails”。
public class ClientViewModel
{
public string CompanyName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullDetails { get { return string.Format("{0}-{1} - {2}", this.CompanyName, this.LastName, this.FirstName)} }
public ClientViewModel(Client c)
{
this.CompanyName = c.CompanyName;
this.FirstName = c.FirstName;
this.LastName = c.LastName;
}
}
..或者只是将FullDetails属性添加到orignal Client类中。
答案 1 :(得分:0)
myLsiTBox.DataSource = context.Clients.select(a=>new {
ID=a.id;
Title=a.CompanyName + "-" + a.LastName + " - " + a.FirstName;
}).ToList();
myLsiTBox.DisplayMember = "Title";
myLsiTBox.ValueMember = "ID";