Bind Entity object to ListBox with multiple fields for DisplayMember

1.1k Views Asked by At

I am using Entity Framework 6 to model a list of clients from a database. I am binding the collection successfully to a listbox. What I can't figure out how to do is to use multiple fields from the object to bind to the DisplayMember property of the Windows Form ListBox.

This works ...

myLsiTBox.DataSource = context.Clients.ToList();
myLsiTBox.DisplayMember = "CompanyName";
myLsiTBox.ValueMember = "id";

This fails ...

myLsiTBox.DataSource = context.Clients.ToList();
myLsiTBox.DisplayMember = "CompanyName" + "-" + "LastName" + " - " + "FirstName";
myLsiTBox.ValueMember = "id";

How do I go about displaying the content from multiple fields in the ListBox?

1

There are 1 best solutions below

0
On

If this was your client:

public class Client
{
    public string CompanyName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

You could make a ClientViewModel and then bind the list box data source to the list of ClientViewModels and set the DisplayMember to "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;
    }
}

..or just add the FullDetails property to the orignal Client class if you can.